题目
基于栈是最好的方案,代码简单,时间复杂度低;dp代码复杂,复杂度高。
法1:栈
Python
基于python的实现非常简练,使用列表(list)实现栈,Python 的列表(list)支持在 尾部高效添加和删除元素(append() 和 pop() 操作时间复杂度为 O(1)),可以轻松模拟栈的行为。
class Solution:
def longestValidParentheses(self, s: str) -> int:
s_array = list(s)
res, n = 0, len(s)
stack = []
for i, val in enumerate(s_array):
if stack and s_array[stack[-1]] == '(' and val == ')':
stack.pop()
if not stack:
res = max(res, i+1) # 长度 = 索引+1
else:
res = max(res, i - stack[-1]) # 长度 = 两个索引之差
else:
stack.append(i)
return res
Java
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;
}
}
本文讨论了使用栈来解决最长有效括号问题的高效方法,对比了栈法的O(N)+O(N)时间复杂度与动态规划的复杂性,展示了基于栈的代码实现和其优势。
845

被折叠的 条评论
为什么被折叠?



