Valid Parentheses
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
思路:
标准的括号匹配题,用stack解决
class Solution {
public:
bool isValid(string str) {
stack<char> s;
for(int i = 0; i < str.length(); i++){
if(str[i] == '(' || str[i] == '[' || str[i] == '{' ){
s.push(str[i]);
} else if(str[i] == ')'){
if(!s.empty() && s.top() == '('){s.pop();}
else{return false;}
} else if(str[i] == ']'){
if(!s.empty() && s.top() == '['){s.pop();}
else{return false;}
} else if(str[i] == '}'){
if(!s.empty() && s.top() == '{'){s.pop();}
else{return false;}
}
} if(!s.empty()){
return false;
} return true;
}
};