• 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;
        }
    };
     
  • 相关阅读:
    cancel-ng-swipe-right-on-child
    css.day.05.eg
    css.day05
    css.day04.eg
    css.day04
    css.day03.eg
    css.day03
    css.day02.eg
    九月十月百度人搜,阿里巴巴,腾讯华为笔试面试八十题(第331-410题)(转)
    阿里巴巴笔试题选解
  • 原文地址:https://www.cnblogs.com/lychnis/p/11723300.html
Copyright © 2020-2023  润新知