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.

 

Analyse: Consider scan the string from two sides. 

Runtime: 8ms

 1 class Solution {
 2 public:
 3     int longestValidParentheses(string s) {
 4         if(s.size() <= 1) return 0;
 5         
 6         int answer = 0, start = -1, depth = 0;
 7         
 8         for(int i = 0; i < s.size(); i++){
 9             if(s[i] == '(') depth++;
10             else{
11                 depth--;
12                 if(depth < 0){
13                     start = i;
14                     depth = 0;
15                 }
16                 else if(depth == 0) answer = max(answer, i - start);
17             }
18         }
19         
20         depth = 0;
21         start = s.size();
22         for(int i = s.size() - 1; i >= 0; i--){
23             if(s[i] == ')') depth++;
24             else{
25                 depth--;
26                 if(depth < 0){
27                     depth = 0;
28                     start = i;
29                 }
30                 else if(depth == 0) answer = max(answer, start - i);
31             }
32         }
33         return answer;
34     }
35 };

 

posted @ 2015-07-21 17:17  amazingzoe  阅读(125)  评论(0编辑  收藏  举报