LeetCode算法系列:32. Longest Valid Parentheses

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/82118092

题目描述:

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

算法描述:

笔者设立了一个栈来保持字符串中未配对的'('的位置信息,同时设立了一个start变量来存放一种位置信息,在这种位置未配对的‘)’出现的次数比未配对的'('多,这个位置之后的有效串不可能与前面的有效串连接在一起,故记录其位置信息重新开始。

扫描字符串

  • 如果碰到'(',直接将其位置信息存放到栈中即可;
  • 如果碰到')',则需要进行判断,如果当前栈为空,则说明这个')'永远不可能有'('与之配对,要重新刷新start信息;如果栈不为空,首先弹出一个栈顶元素与之配对,然后寻找栈中当前栈顶元素 + 1为当前有效字符的开始元素,如果当前栈已空,那么start则为当前有效字符的开始元素。

算法实现:

class Solution {
public:
    int longestValidParentheses(string s) {
        //记录所有'('的位置
        stack<int> st;
        //记录合法的开始位置
        int start = 0;
        int res = 0;
        for(int i = 0; i < s.length(); i ++){
            if(s[i] == '(')st.push(i);
            else if(s[i] == ')'){
                if(st.empty()) start = i + 1;
                else{
                    //首先从堆栈中取出一个元素和')'构成组合
                    st.pop();
                    res = st.empty() ? max(res, i - start + 1) : max(res, i - st.top());
                }
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/82118092