
复制的他人的代码
class Solution {
public boolean checkValidString(String s) {
int n = s.length();
Deque<Integer> leftStack = new LinkedList<>();
Deque<Integer> starStack = new LinkedList<>();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c == '(') {
leftStack.push(i);
} else if (c == '*') {
starStack.push(i);
} else {
if (!leftStack.isEmpty()) {
leftStack.pop();
} else if (!starStack.isEmpty()) {
starStack.pop();
} else {
return false;
}
}
}
while (!leftStack.isEmpty() && !starStack.isEmpty()) {
int leftIndex = leftStack.pop();
int starIndex = starStack.pop();
if (leftIndex > starIndex) return false;
}
return leftStack.isEmpty();
}
}
自己的代码只过了一部分案例
class Solution {
public boolean checkValidString(String s) {
Stack<Integer> stack1=new Stack<>();
Stack<Integer> stack2=new Stack<>();
char[] arr=s.toCharArray();
for(int i=0;i<s.length();i++){
if(arr[i]=='('){
stack1.push(i);
}
if(arr[i]=='*'){
stack2.push(i);
}
if(arr[i]==')'&&!stack1.isEmpty()){
stack1.pop();
}
else if(arr[i]==')'&&!stack2.isEmpty()){
stack2.pop();
}
else
return false;
}
while(!stack1.isEmpty()){
int i=stack1.peek();
if(stack2.isEmpty())
return false;
if(i<stack2.peek()){
stack1.pop();
stack2.pop();
}
else
return false;
}
return true;
}
}
这篇博客探讨了两种不同的代码实现,用于检查一个字符串是否为有效的括号或星号序列。第一种实现使用两个双端队列,分别处理左括号和星号,第二种实现使用两个栈,一个处理左括号,另一个处理星号。文章通过对比两种方法,分析它们的逻辑和在处理特殊情况时的差异,并讨论了各自的优缺点。

被折叠的 条评论
为什么被折叠?



