复制的他人的代码
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;
}
}