32. 最长有效括号

 1 //括号序列合法 <==> 所有前缀和>=0,且总和等于0
 2 
 3 // start当前枚举的这一段的开头
 4 // cnt前缀和
 5 // (=1
 6 // )=-1
 7 // 1、cnt<0 => start = i + 1,cnt = 0
 8 // 2、cnt>0 => 继续做
 9 // 3、cnt==0 => [start,i]是一段合法的括号序列
10 class Solution 
11 {
12 public:
13     int work(string s)
14     {
15         int res = 0;
16         for(int i = 0,start = 0,cnt = 0;i < s.size();i ++)
17         {
18             if(s[i] == '(') cnt ++;//左括号就+
19             else//右括号就-
20             {
21                 cnt --;
22                 if(cnt < 0) start = i + 1,cnt = 0;//如果cnt<0,则更新start,令cnt为0
23                 else if(cnt == 0) res = max(res,i - start + 1);//如果cnt为0,则更新res
24             }
25         }
26         return res;
27     }
28     //从左往右走+从右往左走
29     int longestValidParentheses(string s)//s = "(()" 
30     {
31         int res = work(s);
32         reverse(s.begin(),s.end());//s = ")(("
33         for(auto &c : s) c ^= 1;//左括号变成右括号,右括号变成左括号 s="())"
34         return max(res,work(s));
35     }
36 };

 

posted @ 2020-04-07 22:43  Jinxiaobo0509  阅读(193)  评论(0)    收藏  举报