[LeetCOde32]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.


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;
    }




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值