zoukankan      html  css  js  c++  java
  • 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;
        }
    };
     
  • 相关阅读:
    实验五
    实验一
    实验四
    实验三
    实验8 SQLite数据库操作
    实验7 BindService模拟通信
    实验6 在应用程序中播放音频和视频
    实验5 数独游戏界面设计
    实验4 颜色、字符串资源的使用
    实验五 存储管理实验
  • 原文地址:https://www.cnblogs.com/lychnis/p/11723300.html
Copyright © 2011-2022 走看看