原题
https://leetcode.cn/problems/valid-parentheses/description/
思路
栈
复杂度
时间:O(n)
空间:O(n)
Python代码
class Solution:
def isValid(self, s: str) -> bool:
stack = []
d = {")": "(", "}": "{", "]": "["}
for i, ch in enumerate(s):
if ch in ["(", "{", "["]:
stack.append(ch)
else:
if len(stack) == 0 or stack[-1] != d[ch]:
return False
else:
stack.pop()
return len(stack) == 0
Go代码
func isValid(s string) bool {
stack := []byte{}
m := map[byte]byte{
')': '(',
']': '[',
'}': '{'}
for _, ch := range s {
if ch == '(' || ch == '{' || ch == '[' {
stack = append(stack, byte(ch))
} else {
if len(stack) == 0 || stack[len(stack)-1] != m[byte(ch)] {
return false
} else {
stack = stack[:len(stack)-1]
}
}
}
return len(stack) == 0
}
有效的括号问题解析

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



