标签:
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