Notes:

Do not forget to clean the total and rec.

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

 

posted on 2015-03-20 08:09  keepshuatishuati  阅读(106)  评论(0编辑  收藏  举报