[leetcode] Longest Valid Parentheses

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.

 

思路:传统的括号匹配方法,用堆栈去匹配,遇到'('压入;遇到')',如果栈不为空,匹配成功,弹出栈顶元素,否则匹配不成功。此题需要新加一个标识数组,匹配到的位置标注为1,未匹配到的标注为0,遍历标识数组,统计连续出现1的长度,选择最长的len即为所求结果。

 1 class Solution
 2 {
 3 public:
 4   int longestValidParentheses(string s)
 5   {
 6     int size = s.size();
 7     int *is_match = new int[size];
 8     stack<char> my_stack;
 9     stack<int> temp;
10 
11     for(int i=0; i<size; i++)
12     {
13       if('(' == s[i])
14       {
15         my_stack.push('(');
16         temp.push(i);
17         is_match[i] = 0;
18       }
19       else
20       {
21         if(!my_stack.empty())
22         {
23           my_stack.pop();
24           is_match[i] = 1;
25           is_match[temp.top()] = 1;
26           temp.pop();
27         }
28         else
29           is_match[i] = 0;
30       }
31     }
32 
33     int len = 0, max = 0;
34     for(int i=0; i<size; i++)
35     {
36       if(is_match[i] == 0)
37       {
38         max = max>len ? max : len;
39         len = 0;
40       }
41       else
42         len += is_match[i];
43 
44       if(i+1 == size)
45         max = max>len ? max : len;
46     }
47 
48     return max;
49   }
50 };

 

posted @ 2015-03-20 15:22  imKirin  阅读(133)  评论(0编辑  收藏  举报