一道简单的不能再简单的题,自己竟然写了6遍才通过!!!!!!!!!!!!!!
public class Solution {
public boolean isValid(String s) {
//if (s == null || s.length() < 2) {
if (s == null || s.length() < 2 || s.length() % 2 == 1) {
return false;
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
continue;
}
//1 char temp;
//2 char temp = '';
if (c == ')' || c == ']' || c == '}') {
//3 temp = stack.top();
if (stack.isEmpty()) {
return false;
}
char temp = stack.pop();
//4 if (temp != c) {
// return false;
// }
//5 if ((c == '(' && temp == ')') || (c == '[' && temp == ']') || (c == '{' && temp == '}')) {
if ((temp == '(' && c == ')') || (temp == '[' && c == ']') || (temp == '{' && c == '}')) {
continue;
} else {
return false;
}
}
}
//6
if (!stack.isEmpty()) {
return false;
} else
return true;
}
}