32-Longest Valid Parentheses

来源:互联网 发布:2016开淘宝店审核流程 编辑:程序博客网 时间:2024/06/05 10:54
题目

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

分析

这个有点类似 20-Valid Parentheses
但是要找到Longest 匹配串,所以还是有些变动。

思路一:

  1. 在原来的方法的基础上,添加start 标志最长匹配串开始的index
  2. 相应的stack里面也是存下标(int)而不是存(char)

思路二:

动态规划

实现
class Solution {public:    int longestValidParentheses(string s) {        if (s == "")            return false;        int len = s.length();        //(int)        stack<int> st;        char c;        int curLen = 0, maxLen = 0, start = 0;        for (int i = 0; i < len; i++)        {            c = s[i];            if (c == '(')            {                st.push(i);            }            if (c == ')')            {                if (!st.empty())                {                    st.pop();                    //keypoint                    maxLen = st.empty() ?  max(maxLen, i - start + 1) : max(maxLen, i - st.top());                }                else                {                    start = i + 1;                }            }        }        return maxLen;    }};
原创粉丝点击