LeetCode:32 Longest Valid Parentheses
阿新 • • 發佈:2017-11-20
-s which ini 字串 i++ 不必要 pre find clas , which has length = 4.
1. 題目:
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 "()()"
2. 思路
初始思路
從字符串中每個位置開始,求以該位置開始的最長合法字串長度,然後從這些字串中選出最長的。時間復雜度O(n^2)
改進
可以利用前面已經產生的結果,減少匹配不必要的匹配
1 class Solution { 2 public int longestValidParentheses(String s) { 3 int[] records = new int[s.length()]; 4 int max = 0; 5 for (inti = 1; i < s.length(); i++) { 6 boolean match = false; 7 if ( s.charAt(i) == ‘)‘) { 8 if (s.charAt(i-1) == ‘(‘) { 9 records[i] = 2; 10 match = true; 11 } 12 elseif (records[i-1] > 0 && i - records[i-1] > 0 && s.charAt(i - records[i-1] - 1) == ‘(‘) { 13 records[i] = records[i - 1] + 2; 14 match = true; 15 } 16 if (match) { 17 if (i - records[i] >= 0 && records[i - records[i]] > 0) { 18 records[i] += records[i - records[i]]; 19 } 20 max = max > records[i] ? max : records[i]; 21 } 22 } 23 } 24 return max; 25 } 26 }
LeetCode:32 Longest Valid Parentheses