法1:栈
栈的基础知识介绍:http://www.nhooo.com/java/java-stack.html
必须掌握之算法
Python
class Solution:
def isValid(self, s: str) -> bool:
stack = collections.deque()
for i in range(len(s)):
if len(stack) == 0:
stack.append(s[i])
elif s[i] == ')' and stack[-1] == '(':
stack.pop()
elif s[i] == '}' and stack[-1] == '{':
stack.pop()
elif s[i] == ']' and stack[-1] == '[':
stack.pop()
else:
stack.append(s[i])
return True if len(stack) == 0 else False
Java
class Solution {
public boolean isValid(String s) {
char[] array = s.toCharArray();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < array.length; ++i) {
if (array[i] == '(' || array[i] == '[' || array[i] == '{') {
stack.push(array[i]);
} else if (!stack.isEmpty()
&& (array[i] == ')' && stack.peek() == '('
|| array[i] == ']' && stack.peek() == '['
|| array[i] == '}' && stack.peek() == '{')) {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
}