您的位置:首页 > 其它

[LeetCOde46]Longest Valid Parentheses

2014-06-15 00:17 267 查看
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.

Analysis:

Key point is to save the previous result, e.g. ()(), when the second ( is scanned, the result length should add the
first pair of ().

Some special cases should be considered:

()() max = 4

(()() max = 4

()(() max = 2

We want the complexity to be O(n). Thus iteration is from the first element to the last of the string.

Stack is used to stored the character.

If current character is '(', push into the stack.

If current character is ')',

Case 1: the stack is empty, reset previous result to zero. Here we renew a pointer to store the earliest index.

Case 2: the stack is not empty, pop the top element. if the top element is '(' , (which means a () pair is found),
then if the poped stack is empty, (which means the previous pairs should be added.), len = current pos - previous pos +1; If the poped stack is not empty, len = current pos- index of stack top element.

维护上一次可能出现的左边际

Java

public class Solution {
    class node{
		char c1;
		int index;
		public node(char c1, int index) {
			// TODO Auto-generated constructor stub
			this.c1 = c1;
			this.index = index;
		}
	}
	public int longestValidParentheses(String s) {
        int result = 0;
        int len = s.length();
        if(len<2) return result;
        int lastLeft = 0;
        Stack<node> sta = new Stack<>();
        for(int i=0;i<len;i++){
        	if(s.charAt(i)=='('){
        		sta.push(new node(s.charAt(i), i));
        	}else {
				if(!sta.empty()){
					sta.pop();
					if(sta.empty()){
						result = Math.max(result, i-lastLeft+1);
					}else {
						result = Math.max(result, i-sta.lastElement().index);
					}
				}else {
					lastLeft = i+1;
				}
			}
        }
        return result;
    }
}
c++

int longestValidParentheses(string s) {
     int result = 0;
    int lastleft = 0;
    if(s.size()<2) return result;
    stack<int> sta;
    for(int i=0; i<s.size(); i++){
        if(s[i]=='('){
            sta.push(i);
           }
        else{
            if(!sta.empty()){
                sta.pop();
                if(!sta.empty())
                    result = max(result, i-sta.top());
                else
                    result = max(result,i-lastleft+1);

            }else{
                lastleft = i+1;
            }
        }
    }
    return result;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: