题目
我的题解
解法一
先判断右括号是否打头阵,筛掉这一波。
然后,记录左括号的种类放到list中,后面跟着自己种类的右括号就消除该右括号之前最后一个同种类的左括号,后面跟着左括号就直接放进list,在自己种类的右括号之前出现其他种类的右括号为false。
class Solution {
public boolean isValid(String s) {
String braceList = "(){}[]";
// 当输入为空字符串or输入长度为奇数,返回false
if (s.length() == 0 || s.length() % 2 != 0) {
return false;
}
int leftIndex = 0;
int leftIndexInBL = braceList.indexOf(s.charAt(0));
// 第一个值为右括号,返回false
if (leftIndexInBL % 2 != 0) {
return false;
}
StringBuilder stb = new StringBuilder(s);
int thisIndexInBL;
int thisIndex = 1;
while (stb.length() > 0) {
thisIndexInBL = braceList.indexOf(stb.charAt(thisIndex));
// 是左括号
if (thisIndexInBL % 2 == 0) {
leftIndex = thisIndex;
leftIndexInBL = thisIndexInBL;
thisIndex++;
if (thisIndex > stb.length() - 1) { // 如果最后都是左括号,则为false
return false;
}
} else if (thisIndexInBL == leftIndexInBL + 1) { // 是同类右括号
stb.delete(thisIndex - 1, thisIndex + 1);
leftIndex--;
// stb空了or左索引前面没值,当前索引为最后一个
if (stb.length() == 0) {
return true;
} else if (leftIndex < 0 && thisIndex != stb.length() - 1) { // 左边没有值,右边没到头,则左索引和当前索引跳到0
thisIndex = 0;
leftIndex = thisIndex;
} else { // 左边还有值,则左索引和当前索引左移两位
thisIndex = Math.max(thisIndex - 2, 0); // 防止溢出
leftIndex = thisIndex;
}
// 左边还有值则左索引直接左移,随上
leftIndexInBL = braceList.indexOf(stb.charAt(leftIndex));
} else { // 是不同类右括号
return false;
}
// 剩下的全是左括号
}
return true;
}
}
解法二
还有一个方法是找到括号对,一对一对消除,最后什么都不剩了就是true,否则是false。不用折腾索引,方便很多。但是这个方法比上个方法用时和内存消耗都更大,可能是replace方法的锅。
class Solution {
public boolean isValid(String s) {
int length = s.length();
for (int i = 0; i < length; i++){
s = s.replace("[]","");
s = s.replace("{}","");
s = s.replace("()","");
}
return s.isEmpty();
}
}
2021.05.23 更新解法三
解法三:使用栈
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
// 如果字符串长度是单数,因为不可能成双成对,直接返回false
if (s.length() % 2 != 0) {
return false;
}
for (int i = 0; i < s.length(); i++) {
char thisChar = s.charAt(i);
switch (thisChar) {
case '(':
case '{':
case '[':
stack.push(thisChar);
break;
case ')':
if (stack.isEmpty() || stack.pop() != '(') {
return false;
} else {
break;
}
case '}':
if (stack.isEmpty() || stack.pop() != '{') {
return false;
} else {
break;
}
case ']':
if (stack.isEmpty() || stack.pop() != '[') {
return false;
} else {
break;
}
}
}
return stack.isEmpty();
}
}
总结
- 要熟悉使用Java库中的函数,会简洁许多。
- 查看栈的使用总结。