[leetcode] 20. 有效的括号
括号匹配,用栈即可。高中时第一次学栈后做的第一个题。。
class Solution {
public boolean isValid(String s) {
Stack<Character> characterStack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '(':
case '[':
case '{':
characterStack.push(s.charAt(i));
break;
case ')':
if (!characterStack.isEmpty() && characterStack.peek() == '(') {
characterStack.pop();
break;
} else {
return false;
}
case ']':
if (!characterStack.isEmpty() && characterStack.peek() == '[') {
characterStack.pop();
break;
} else {
return false;
}
case '}':
if (!characterStack.isEmpty() && characterStack.peek() == '{') {
characterStack.pop();
break;
} else {
return false;
}
}
}
return characterStack.isEmpty();
}
}