678. Valid Parenthesis String
Medium
68824FavoriteShare
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
class Solution {
public:
bool checkValidString(string s) {
stack<int> Left;
stack<int> Star;
for(int i = 0;i < s.length();i ++){
if(s[i] == '('){
Left.push(i);
}
else if(s[i] == '*'){
Star.push(i);
}
else{
if(!Left.empty()){
Left.pop();
}
else if(!Star.empty()){
Star.pop();
}
else{
return false;
}
}
}
while(!Left.empty() && !Star.empty()){
if(Left.top() > Star.top()){
return false;
}
Left.pop();Star.pop();
}
if(!Left.empty()){return false;}
else{return true;}
}
};
标签:匹配,string,扩展,else,括号,parenthesis,Star,empty,Left From: https://blog.51cto.com/u_13121994/5798503