• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
32. Longest Valid Parentheses *HARD*

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

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

int longestValidParentheses(string s) {
    int maxLen = 0;
    int lastError = -1;
    vector<int> stack;
    for(int i=0; i<s.size(); i++)
    {
        if (s[i] == '(')
            stack.push_back(i);
        else if (s[i] == ')')
        {
            if (stack.size()>0 )
            {
                stack.pop_back();
                int len;
                if (stack.size()==0)
                    len = i - lastError;
                else
                    len = i - stack.back();
                if (len > maxLen)
                    maxLen = len;
            }
            else
                lastError = i;
        }
    }
    return maxLen;
}

 

posted on 2016-03-05 12:01  ArgenBarbie  阅读(179)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3