[leetcode]Longest Valid Parentheses

来源:互联网 发布:有赞 知乎 编辑:程序博客网 时间:2024/06/06 00:00

题目介绍:

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.

Subscribe to see which companies asked this question

根据题目要求,首先想到了判断一串字符串是否为合法字符串的方法。思路是:采用栈的方法。每次将'('左括号入栈,遇到')'右括号时,如果栈为空表示无法匹配,则为不合法的字符串,否则弹出一个左括号。到最后判断是栈是否为空,不为空则表示是不合法的。

判断字符串是否是合法的函数如下:

public boolean isValid(String s){if(s==null||s.length()<2)return false;int len=s.length();if(len%2!=0)return false;Stack<Character> stack=new Stack<Character>();for(int i=0;i<s.length();i++){if(s.charAt(i)=='(') stack.push('(');else{if(stack.isEmpty())return false;else stack.pop();}}if(stack.isEmpty())return true;return false;}


根据以上思路,可以维护一个数组,用来存储字符串中的某些位是否是合法的括号,即是否被匹配,然后顺序扫描数据,得到最长的连续为true的即可。算法复杂度为O(n).

本题目的解法代码如下:

public int longestValidParentheses(String s) {        if(s==null||s.length()<2)return 0;int len=s.length();Stack<Character> stack=new Stack<Character>();Stack<Integer> stackNum=new Stack<Integer>();boolean isValid[]=new boolean[len];for(int i=0;i<len;i++) isValid[i]=false;for(int i=0;i<len;i++){if(s.charAt(i)=='('){stack.push('(');stackNum.push(i);}else{if(!stack.isEmpty()){stack.pop();int k=stackNum.pop();isValid[i]=true;isValid[k]=true;}}}int result=0;int max=0;for(int i=0;i<len;i++){if(isValid[i]){result++;while(i+1<len&&isValid[i+1]){result++;i++;}}else{if(result>max)max=result;result=0;}if(result>max)max=result;}return max;    }





1 0
原创粉丝点击