问题描叙:给定一个字符串s包含'(',')','[',']','{','}'。判断这串字符串括号能否匹配。
Example:
Given s = "[({})}",
return false.
思路:使用栈来处理括号的匹配,如果是左边的符号,则入栈;否则,判断当前右符号是否与栈顶元素相配对。若能配对,则出栈,然后考察下一个符号;否则,返回false。所有符号考察完之后,如果栈为空返回true;不为空返回false。
Code:
public boolean isValid(String s) {
char[] sToChar = s.toCharArray();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < sToChar.length; i++) {
if (sToChar[i] == '(' || sToChar[i] == '{' || sToChar[i] == '[') {
stack.push(sToChar[i]);
}
else {
//判断字符串中,右符号前是否有左符号
if (!stack.empty()) {
if (sToChar[i] == ')' && stack.peek().equals('(')) {
stack.pop();
continue;
}
if (sToChar[i] == ']' && stack.peek().equals('[')) {
stack.pop();
continue;
}
if (sToChar[i] == '}' && stack.peek().equals('{')) {
stack.pop();
continue;
}
return false;
}
else {
return false;
}
}
}
if (stack.empty()) {
return true;
}
else {
return false;
}
}
Code改进:
public boolean isValid(String s) {
//判断字符串长度是否为偶数
if(s.length() % 2 == 1) {
return false;
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
stack.push(s.charAt(i));
}
else {
//判断字符串中,右符号前是否有左符号
if (!stack.empty()) {
if (s.charAt(i) == ')' && stack.peek().equals('(')) {
stack.pop();
continue;
}
if (s.charAt(i) == ']' && stack.peek().equals('[')) {
stack.pop();
continue;
}
if (s.charAt(i) == '}' && stack.peek().equals('{')) {
stack.pop();
continue;
}
return false;
}
else {
return false;
}
}
}
if (stack.empty()) {
return true;
}
else {
return false;
}
}