标签:character 依次 思路 字符 bst idp 遍历 rac 出栈
Given a string containing just the characters ‘(‘ and ‘)‘, find the length of the longest valid (well-formed) parentheses substring.
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
采用栈数据结构。栈中存放各字符的下标。初始时里面放入-1。
遍历结束后,需要用 n - stack.peek() - 1 更新 max。
class Solution {
public int longestValidParentheses(String s) {
int max = 0, n = s.length(), temp, index = 0;
if(n == 0){
return 0;
}
int[] stack = new int[n + 1];
stack[index++] = -1;
for(int i = 0; i < n; i++){
if(s.charAt(i) == ‘(‘ || (temp = stack[index - 1]) == -1 ||
s.charAt(temp) == ‘)‘){
if((temp = i - stack[index - 1] - 1) > max){
max = temp;
}
stack[index++] = i;
}
else{
index--;
}
}
if((temp = n - stack[index - 1] - 1) > max){
max = temp;
}
return max;
}
}
标签:character 依次 思路 字符 bst idp 遍历 rac 出栈
原文地址:https://www.cnblogs.com/echie/p/9589097.html