标签:++ etc ISE empty rip bool ems character amp
括号匹配,用栈即可。高中时第一次学栈后做的第一个题。。
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();
}
}
标签:++ etc ISE empty rip bool ems character amp
原文地址:https://www.cnblogs.com/acbingo/p/9250790.html