括号匹配,用栈即可。高中时第一次学栈后做的第一个题。。
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();
}
}
原文地址:https://www.cnblogs.com/acbingo/p/9250790.html
时间: 2024-10-29 18:03:41