继续leetcode hard模式,这题整了我好久,想了好几种方法,最终都没能通过oj都时间复杂度,然后忍不住看了答案,简洁到尿,想死, 上代码:
import java.util.Stack;
public class Solution {
public int longestValidParentheses(String str) {
int n = str.length();
Stack<Integer> stk = new Stack<>();
stk.push(-1);
int result = 0;
for (int i=0; i<n; i++)
{
if (str.charAt(i) == '('){
stk.push(i);
}else
{
stk.pop();
if (!stk.empty()){
result = Math.max(result, i - stk.peek());
}
else{
stk.push(i);
}
}
}
return result;
}
}