32. Longest Valid Parentheses

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 "()()"

在给定字符串中找到子串,要求子串的括号是匹配的,并且长度最长.
解决办法,遍历这个字符串,把匹配的括号全部消除,用到的数据结构是stack.
stack里面保存索引,假如字符串整个括号都是匹配的,那么stack最终为空.
如果不为空,只要数出相邻的索引距离即可
class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st;
        for(int i=0;i<s.size();++i)
        {
            if(')'==s[i]&&!st.empty()&&'('==s[st.top()])
                st.pop();
            else
                st.push(i);
        }
        if(st.empty())return s.size();
        int res=0;
        int tmp1=0,tmp2=s.size();
        while(!st.empty())
        {
            tmp1=st.top();
            st.pop();
            res=max(res, tmp2-tmp1-1);
            tmp2=tmp1;
        }
        res=max(res,tmp2);
        return res;
    }
};
 
原文地址:https://www.cnblogs.com/lychnis/p/11723300.html