Given a string containing only the three character classes :(,) and *, write a function to test whether the string is a valid string. Valid string has the following rules:
Any left parenthesis (must have a corresponding right parenthesis).
Any right parenthesis) must have a corresponding left parenthesis (.
Left parenthesis (must be before the corresponding right parenthesis).
* May be viewed as a single right parenthesis), or a single left parenthesis (or an empty string.
An empty string It is also considered a valid string.
Ideas:
The (and each stack, and then put regarded (traversing the string), then discuss as) case,
at this time (the index must be greater than before deemed)
class Solution {
public boolean checkValidString(String s) {
stack<int> left,star;
for(int i=0;i<s.size();i++){
if(s[i]=='(') left.push(i);
else if(s[i]=='*') star.push(i);
else {
if(left.empty() && star.empty()) return false;
if(!left.empty()) left.pop();
else
star.pop();
}
}
while(!left.empty()&&!star.empty()){
if(left.top()>star.top)return false;
left.pop();
star.pop();
}
return left.empty();
}
}