Leetcode之 Longest Valid Parentheses
阿新 • • 發佈:2018-12-28
題目:
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())
" Output: 4 Explanation:The longest valid parentheses substring is"()()"
程式碼:
class Solution { public: int longestValidParentheses(string s) { int sum = 0, record = 0, count = 0, max1 = INT_MIN,max2=INT_MIN; int len = s.length(); bool flag = false; for (int i = 0; i < len; i++) { if (s[i] == '(') { sum++; record++; flag = true; } if (flag&&s[i] == ')') { sum--; if (sum == 0) { count += record * 2; record = 0; } if (sum < 0) { max1 = max1 > count ? max1 : count; count = 0; sum=0; flag = false; } } } max1 = max1 > count ? max1 : count; sum = 0; record = 0; count = 0; flag = false; for (int i = len - 1; i >= 0; i--) { if (s[i] == ')') { sum++; record++; flag = true; } if (flag&&s[i] == '(') { sum--; if (sum == 0) { count += record * 2; record = 0; } if (sum < 0) { max2 = max2 > count ? max2 : count; count = 0; sum=0; flag = false; } } } max2 = max2 > count ? max2 : count; return max1 > max2 ? max1 : max2; } };
思路:
1、用一個數字給左括號,右括號計數
往右走的時候左括號加右括號減,往左走記右括號加左括號減。
計數小於零的時候重置計數
一路下來記錄最長的就完事了。
2、從向左方向和向右方向都需要遍歷
3、值得注意的點:當計數小於0的時候要給它重置為0