qingcheng奕  

http://oj.leetcode.com/problems/longest-valid-parentheses/

最大括号匹配长度,括号是可以嵌套的。

 1 #include <string>
 2 #include <stack>
 3 #include <vector>
 4 #include <iostream>
 5 using namespace std;
 6 class Solution {
 7 public:
 8     int longestValidParentheses(string s) {
 9         const int s_len = s.size();
10 
11         stack<int> indexstack;
12         vector<bool> flagvector;
13         int templen = 0;
14         int maxlen = 0;
15         flagvector.resize(s_len);
16 
17         for(int index = 0;index<s_len;index++)
18             flagvector[index] = false;
19 
20         for(int i = 0;i<s_len;i++)
21         {
22             if(s[i]==')')
23             {
24                 if(indexstack.size()!=0)
25                 {
26                     flagvector[indexstack.top()] = true;
27                     flagvector[i] = true;
28                     indexstack.pop();
29                 }
30  
31             }
32             if(s[i]=='(')
33             {
34                 indexstack.push(i);
35             }
36         }
37         for(int index = 0;index<s_len;index++)
38         {
39             if(flagvector[index]==false)
40             {
41                 maxlen = maxlen>templen?maxlen:templen;
42                 templen = 0;
43             }
44             else
45                 templen++;
46         }
47         maxlen = maxlen>templen?maxlen:templen;
48         return maxlen;
49     }
50 }; 
View Code
#include <iostream>
#include "cla.h"
using namespace std;
int main()
{
    Solution * mysolution = new Solution();
    string str = "";
    cout<<mysolution->longestValidParentheses(str)<<endl;
    return 0;
}

 

posted on 2013-10-26 10:49  qingcheng奕  阅读(129)  评论(0)    收藏  举报