码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 32. Longest Valid Parentheses

时间:2015-02-05 00:41:45      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

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.

[Solution]

用bool数组记录可以组成成对括号的位置,再用动态规划求解最大连续的true的个数。

 1 int longestValidParentheses(string s) 
 2     {
 3         stack<int> leftPos;
 4         vector<bool> table(s.size(), false);
 5         int global_max = 0, suffix_max = 0;
 6         
 7         for (int i = 0; i < s.size(); i++)
 8         {
 9             if (s[i] == ()
10                 leftPos.push(i);
11             else if (!leftPos.empty())
12             {
13                 table[i] = true;
14                 table[leftPos.top()] = true;
15                 leftPos.pop();
16             }
17         }
18         
19         for (int i = 0; i < table.size(); i++)
20         {
21             if (table[i] == true)
22                 suffix_max++;
23             else
24                 suffix_max = 0;
25             if (global_max < suffix_max)
26                 global_max = suffix_max;
27         }
28         
29         return global_max;
30     }

 

leetcode 32. Longest Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4273515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!