题目
思路
- 一个栈存左括号位置 一个栈存*位置 遇到右括号出来匹配
- 要注意一点 如果left后面已经没有*号了,说明是false
代码
public boolean checkValidString(String s) {
Stack<Integer> left_index = new Stack<>();
Stack<Integer> star_index = new Stack<>();
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(c=='(') left_index.push(i);
else if(c=='*') star_index.push(i);
else {
if(left_index.empty() && star_index.empty()) return false;
if(!left_index.empty()){
left_index.pop();
continue;
}
if(!star_index.empty()) star_index.pop();
}
}
while (!left_index.empty()){
if(star_index.empty()) return false;
int left = left_index.pop();
int star = star_index.pop();
if(star<left) return false;
}
return true;
}