[LeetCode] 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.

 

Another string matching problem, this time I finish this problem in 30 minutes! and got ACCEPTED on my first submission. damn thats feels so good.
I discoverd an easy way to deal with it which I called it "mark&count" I'll explain it below, its easy and I think everyone could understand it.

 

init an array r with same size of string, containing int. 
iterate the string with index variable i
use stack for pair matching, that is, pushing the index in whenever encounter '(' and pop when ')' . 
when pop, mark all the position from stack.top() to i in r
after iterate finish, begin iterate r, count for longest marked position then thats the answer.

 

AC:

 1 class Solution {
 2 public:
 3     int longestValidParentheses(string s) {
 4             stack<int> t;
 5     int len = s.size();
 6     vector<int> r(len, 0);
 7     
 8     for (int i=0; i<len; i++){
 9         if (s[i] == '('){
10             t.push(i);
11         }
12         else if (s[i] == ')'){
13             if (!t.empty()){
14                 int top = t.top();
15                 t.pop();
16                 for (int j=top; j<i+1; j++){
17                     r[j] = 1;
18                 }
19             }
20         }
21     }
22     int max=0,sum=0;
23     for (int i=0; i<len; i++){
24         if (r[i]){
25             if (++sum > max){
26                 max = sum;
27             }
28         }else{
29             sum = 0;
30         }
31     }
32     return max;
33     }
34 };

 

posted @ 2014-04-23 21:27  Agentgamer  阅读(210)  评论(0编辑  收藏  举报