LeetCode: Longest Valid Parentheses [031]

来源:互联网 发布:现在淘宝客服工资多少 编辑:程序博客网 时间:2024/06/06 00:30

【题目】


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.


【题意】

给定一个字符串,判定其中最长的有效括号子串的长度。


【思路】

所谓有效括号串可参见“vaid parentheses”
本题的思路大体相同,仍然是维护一个栈,但入栈的元素不在是"("或")",而是字符串中相应的索引位。
当我们扫描完一遍字符串时,有效的连续括号子串会被从栈中清除,栈中留下的是剩余字符的索引位。
我们只需要计算剩余字符之间最大的索引间隔是多少即可。


【代码】

class Solution {public:    bool isPair(char left, char right){        return left=='('&&right==')';    }    int longestValidParentheses(string s) {        int len=s.length();        if(len==0)return len;        int result=0;       //初始化result        stack<int> st;      //辅助栈,存放相应字符的索引位        for(int i=0; i<len; i++){            if(st.empty())st.push(i);            else{                if(isPair(s[st.top()],s[i]))st.pop();                else st.push(i);            }        }        //求最大子串长度        int prev=len;        while(!st.empty()){            if(prev-st.top()-1>result)result=prev-st.top()-1;            prev=st.top();            st.pop();        }        if(prev>result)result=prev; //别忘了开头的那个子串        return result;    }};


0 0
原创粉丝点击