题目
基于栈是最好的方案,代码简单,时间复杂度低;dp代码复杂,复杂度高。
法1:栈
O(N) + O(N)
思路:
复杂度:
class Solution {
public int longestValidParentheses(String s) {
List<Integer> stack = new ArrayList<>();
stack.add(-1); // 哨兵索引
int max = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '(') {
stack.add(i);
} else {
stack.remove(stack.size() - 1);
if (stack.isEmpty()) {
stack.add(i);
} else {
max = Math.max(max, i - stack.get(stack.size() - 1));
}
}
}
return max;
}
}