第一感是用个stack,然后压栈出栈,看看是不是匹配,没有考虑更多技巧。
public class Solution {
public boolean isValid(String s) {
int length = s.length();
Stack<String> stack = new Stack<String>();
for (int i = 0; i < length; ++i) {
String x = s.substring(i, i + 1);
if (x.equals("(") || x.equals("[") || x.equals("{")) {
stack.push(x);
} else if (x.equals(")")) {
if (stack.isEmpty() || !"(".equals(stack.pop())) {
return false;
}
} else if (x.equals("]")) {
if (stack.isEmpty() || !"[".equals(stack.pop())) {
return false;
}
} else if (x.equals("}")) {
if (stack.isEmpty() || !"{".equals(stack.pop())) {
return false;
}
} else {
return false;
}
}
return stack.isEmpty() ? true : false;
}
}