Longest Valid Parentheses
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.
Subscribe to see which companies asked this question
Show Similar Problems
class Solution { public: int longestValidParentheses(string s) { int length = s.length(); if (0 == length) { return 0; } int max_len = 0; int i = 0; int start = 0; stack<int> s_i; for (i=0; i<length; i++) { if (s[i] == '(') { s_i.push(i); } else if (s[i] == ')' && !s_i.empty()) { //int left = s_i.top(); s_i.pop(); if (s_i.empty()) { max_len = max(max_len, i - start + 1); } else { max_len = max(max_len, i - s_i.top()); cout << "max len when not empty is " << max_len << endl; } } else { start = i + 1; } } return max_len; } };
posted on 2016-02-06 20:03 walkwalkwalk 阅读(194) 评论(0) 收藏 举报
浙公网安备 33010602011771号