LeetCode 32 Longest Valid Parentheses 最大合法括号匹配长度计算 动态规划算法有待学习

来源:互联网 发布:淘宝美工课程介绍 编辑:程序博客网 时间:2024/05/21 21:35

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.


解题思路:一开始的时候,被这道题的动态规划的标签吓到了,由于我目前对动态规划这方面的知识掌握并不透彻,我通过上网找到一个简单的解题方案,居然不需要动态规划。办法如下,设置一个数组,全部初始化为0.数组的每一位对应字符串的每一位,若括号匹配,则置为1.在遍历完整个字符串的时候,找到最长的连续匹配的长度,即为我们要求的结果。因为对于”()(()“这个测试用例,结果为2,为什么呢?因为第三个括号无法匹配,截断了,但如果我们不设置数组来记录的话,则无法在确定匹配后,求出最大匹配长度。

        这里复习了java版的stack,java版的top函数就是peek()...经常容易忘记这一点。

        当然,还有动态规划的解法,我也把他给出在下面,还有待学习。

代码如下:

 public int longestValidParentheses(String s) {   Stack stack = new Stack(); // 创建堆栈对象      int len = s.length();   int []num= new int[len];   Arrays.fill(num, 0);   for (int i = 0; i < len; i++) {if(s.charAt(i)=='('){stack.push(i);}else if(s.charAt(i)==')' && !stack.empty()){num[(int) stack.peek()]=1;num[i]=1;stack.pop();}}   int tmax=0;   int max =0;   for (int j = 0; j < len; j++) {if(num[j]==1){tmax++;}else{tmax=0;}if(tmax>=max){max =tmax;}}   return max;    }

参考文章:http://www.cnblogs.com/easonliu/p/3637429.html

动态规划代码如下:

http://blog.csdn.net/cfc1243570631/article/details/9304525


0 0
原创粉丝点击