題目
Given a string containing only three types of characters: ‘(’, ‘)’ and ‘*’, write a function to check whether this string is valid. We define the validity of a string by these rules:
Any left parenthesis ‘(’ must have a corresponding right parenthesis ‘)’.
Any right parenthesis ‘)’ must have a corresponding left parenthesis ‘(’.
Left parenthesis ‘(’ must go before the corresponding right parenthesis ‘)’.
‘*’ could be treated as a single right parenthesis ‘)’ or a single left parenthesis ‘(’ or an empty string.
An empty string is also valid.
- Example 1:
- Input: “()”
- Output: True
- Example 2:
- Input: “(*)”
- Output: True
- Example 3:
- Input: “(*))”
- Output: True
- Note:
The string size will be in the range [1, 100].
解答
class Solution {
public boolean checkValidString(String s) {
// 思路:左右括號匹配,*可以作爲任何單獨的:左括號、右括號、空符號,採用兩個棧來記錄左括號、星的位置
if(s==null||s.length()==0){
return true;
}
// 定義2個棧來存儲對應下標
Stack<Integer>leftStack=new Stack<>();
Stack<Integer> starStack=new Stack<>();
char[] chs=s.toCharArray();
for(int i=0;i<chs.length;i++){
char ch=chs[i];
if(ch=='('){
leftStack.push(i);
}else if(ch=='*'){
starStack.push(i);
}else{
// 判斷左括號是否在星括號的右側
if(leftStack.isEmpty()&&starStack.isEmpty()){
return false;
}else if(!leftStack.isEmpty()){
leftStack.pop();
}else if(!starStack.isEmpty()){
starStack.pop();
}
}
}
// 判斷leftStack是否爲空,若不爲空則校驗兩個棧的棧頂位置是否存在左括號在*括號的右邊的情況,若存在則返回false
while(!leftStack.isEmpty()){
if(!starStack.isEmpty()){
if(leftStack.peek()>starStack.peek()){
return false;
}else{
leftStack.pop();
starStack.pop();
}
}else{
return false;
}
}
return true;
}
}