020_有效的括号
2026/4/17小于 1 分钟
020_有效的括号
简单Java
class Solution {
public boolean isValid(String s) {
int[] stack = new int[s.length()];
int index = 0;
for(int i = 0;i < s.length();i++){
char c = s.charAt(i);
if(index == 0 && (c == ')' || c == ']' || c == '}')){
return false;
}
if(c == '(' || c == '[' || c == '{'){
stack[index] = s.charAt(i);
index++;
}else if(c == ')' && stack[index-1] == '(' || c == ']' && stack[index-1] == '[' || c == '}' && stack[index-1] == '{'){
index--;
}else{
return false;
}
}
if(index == 0){
return true;
}else {
return false;
}
}
}Python
class Solution:
def isValid(self, s: str) -> bool:
stack = deque()
for i in s:
if i == ')' and len(stack) > 0 and stack.pop() == '(': continue
elif i == ']' and len(stack) > 0 and stack.pop() == '[': continue
elif i == '}' and len(stack) > 0 and stack.pop() == '{': continue
elif i == '(' or i == '[' or i == '{': stack.append(i)
else: return False
return True if len(stack) == 0 else False