码迷,mamicode.com
首页 > 其他好文 > 详细

32. Longest Valid Parentheses

时间:2019-10-23 00:33:50      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:lan   put   int   ack   size   character   并且   return   longest   

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

 

 

32. Longest Valid Parentheses

标签:lan   put   int   ack   size   character   并且   return   longest   

原文地址:https://www.cnblogs.com/lychnis/p/11723300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!