给你一个只包含
'('
和')'
的字符串,找出最长有效(格式正确且连续)括号子串的长度。
代码如下:
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;}
}