給你一個只包含?
'('
?和?')'
?的字符串,找出最長有效(格式正確且連續)括號子串的長度。?
?
?
?
?
?
?代碼如下:
class Solution {public int longestValidParentheses(String str) {Stack<Integer> s = new Stack<>();int res = 0;int start = 0;for(int i = 0; i < str.length(); i++){if(str.charAt(i) == '('){s.push(i);}else {if(!s.isEmpty()) {s.pop();if(s.isEmpty()){//() () () res = Math.max(res,i - start + 1);}else {//( ( ( ) ) (res = Math.max(res, i - s.peek());}}else { // )()()start = i + 1;}}}return res;}
}
?
?