原题链接在这里:https://leetcode.com/problems/longest-valid-parentheses/
和Largest Rectangle in Histogram都是往栈内存index.
生成一个stack, 从头往后扫string, 遇到'(', 就把当前index存入到stack中。
当遇到 ')'时要看当前stack是后为空,若为空,更新新起点start = i+1;
若不为空,就pop出来一个index,然后再看stack是否为空:
若为空,则最大长度maxLength更新为Math.max(maxLength, i-start+1);
若不为空,则maxLength更新为Math.max(maxLength,i-stk.peek()), 因为"( ( )"返回的长度是3不是2. 这里的三个括号配对是合法的。
Time O(n), Space O(n).
AC Java:
public class Solution {
public int longestValidParentheses(String s) {
if(s == null || s.length() == 0){
return 0;
}
Stack<Integer> stk = new Stack<Integer>();
int maxLength = 0;
int start = 0;
for(int i = 0; i<s.length(); i++){
if(s.charAt(i) == '('){
stk.push(i);
}
else{
if(stk.isEmpty()){
start = i+1;
}else{
int index = stk.pop();
if(stk.isEmpty()){
maxLength = Math.max(maxLength, i-start+1);
}else{
maxLength = Math.max(maxLength, i-stk.peek());
}
}
}
}
return maxLength;
}
}