Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

SOLUTION 1:

1. 使用栈来保存'('

2. tmp 表示当前计算的一套完整的括号集的长度。完整的指的是消耗掉栈中所有的'('.

3. sum 表示数个完整的括号集的总长。

例子:

有一套完整的括号集,可以加到前面的一整套括号集上
                     () (()())
                      1    2  第二套括号集可以加过来

4. 不完整的括号集:

这种情况也是需要计算的。也可能是一个未完成的括号集,比如:

() (()()  在这里 ()() 是一个未完成的括号集,可以独立出来计算,作为
阶段性的结果

5. 栈为空时,出现一个')',可以将sum置0.

 public class Solution {
public int longestValidParentheses(String s) {
if (s == null) {
return 0;
} Stack<Integer> stk = new Stack<Integer>();
int sum = 0;
int tmp = 0; int max = 0; for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i); if (c == '(') {
stk.push(i);
} else {
if (stk.isEmpty()) {
// 栈中没有'(',出现')', 则必须重置计算
sum = 0;
continue;
} // count the temporary lenght:
// like: (()()()
// tmp = 2.
tmp = i - stk.pop() + 1;
if (stk.isEmpty()) {
// 有一套完整的括号集,可以加到前面的一整套括号集上
// () (()())
// 1 2 第二套括号集可以加过来
sum += tmp;
max = Math.max(sum, max);
} else {
// 也可能是一个未完成的括号集,比如:
// () (()() 在这里 ()() 是一个未完成的括号集,可以独立出来计算,作为
// 阶段性的结果
tmp = i - stk.peek();
max = Math.max(tmp, max);
}
}
} return max;
}
}

2015.1.3 redo:

 public class Solution {
public int longestValidParentheses(String s) {
if (s == null) {
return 0;
} int len = s.length();
Stack<Integer> stk = new Stack<Integer>(); int sum = 0;
int max = 0;
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c == '(') {
stk.push(i);
} else {
if (stk.isEmpty()) {
// The sequence is cut off.
sum = 0;
} else {
int tmp = i - stk.pop() + 1;
if (stk.isEmpty()) {
sum += tmp;
max = Math.max(max, sum);
} else {
max = Math.max(max, i - stk.peek());
}
}
}
} return max;
}
}

GIT HUB 代码:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/LongestValidParentheses.java

LeetCode: Longest Valid Parentheses 解题报告的更多相关文章

  1. [LeetCode] Longest Valid Parentheses 解题思路

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  2. [LeetCode] Longest Valid Parentheses 最长有效括号

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  3. [Leetcode] longest valid parentheses 最长的有效括号

    Given a string containing just the characters'('and')', find the length of the longest valid (well-f ...

  4. [LeetCode] Longest Valid Parentheses

    第一种方法,用栈实现,最容易想到,也比较容易实现,每次碰到‘)’时update max_len,由于要保存之前的‘(’的index,所以space complexity 是O(n) // 使用栈,时间 ...

  5. [LeetCode] Longest Valid Parentheses 动态规划

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  6. LeetCode: Valid Parentheses 解题报告

    Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', det ...

  7. [LeetCode] Longest Valid Parentheses -- 挂动态规划羊头卖stack的狗肉

    (Version 1.3) 这题在LeetCode上的标签比较有欺骗性,虽然标签写着有DP,但是实际上根本不需要使用动态规划,相反的,使用动态规划反而会在LeetCode OJ上面超时.这题正确的做法 ...

  8. leetcode: Longest Valid Parentheses分析和实现

    题目大意:给出一个只包含字符'('和')'的字符串S,求最长有效括号序列的长度. 很有趣的题目,有助于我们对这种人类自身制定的规则的深入理解,可能我们大多数人都从没有真正理解过怎样一个括号序列是有效的 ...

  9. LeetCode: Longest Common Prefix 解题报告

    Longest Common Prefix Write a function to find the longest common prefix string amongst an array of ...

随机推荐

  1. uniq命令 (转)

    uniq命令可以去除排序过的文件中的重复行,因此uniq经常和sort合用.也就是说,为了使uniq起作用,所有的重复行必须是相邻的. uniq语法 [root@www ~]# uniq [-icu] ...

  2. 在js里双引号里又加单引号的解决方案常用WdatePicker

    EndTime: '<input name="EndTime" type="text" class="editable center decim ...

  3. 谷歌浏览器禁止window.close的问题

    当一个窗口不是通过window.open或者window.showModalDialog打开的时候,调用JS的window.close() 谷歌浏览器会提示如下警告,并拒绝执行 Scripts may ...

  4. Tomcat SSL配置 Connector attribute SSLCertificateFile must be defined when using SSL with APR解决

    原文地址:http://blog.csdn.net/kissliux/article/details/17392003 Tomcat 6版本配置SSL过程有两步: 1.用JDK自带的keytool.e ...

  5. shell脚本死循环判断nginx日志reqest_time时间大于3秒是否增加,若增加发送相关日志信息到开发人员

    #!/bin/bash while [ 1 ] do pre_request_time_count=`cat /var/log/nginx/access.log |awk '{print $NF}'| ...

  6. eclipse新建maven工程的各种坑

    尽量按照最后强烈推荐的那篇创建maven工程.  1.jsp文件头报错 2.xml配置文件头红叉 3.Archive for required library...blabla 4.pom依赖出错 5 ...

  7. HDUOJ---What Are You Talking About

    What Are You Talking About Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 102400/204800 K ...

  8. Loading...加载图收集

    收集来源:http://cs.fangjia.com/zoushi/

  9. shell 基本学习

    1)查看当前shell echo $SHELL 2)查看兼容shell more /etc/shells 3) 脚本第一行 #!/bin/bash 4) 变量(变量名称的开头是一个字母或下划线符号,后 ...

  10. 红黑树 - C++代码实现

    红黑树的介绍 红黑树(Red-Black Tree,简称R-B Tree),它一种特殊的二叉查找树.红黑树是特殊的二叉查找树,意味着它满足二叉查找树的特征:任意一个节点所包含的键值,大于等于左孩子的键 ...