题目链接:https://leetcode.com/problems/valid-parentheses/
Runtimes:3ms
1、问题
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.
2、分析
先进后出的道理,括号的匹配,简单的题目。
3、小结
陷阱:1、奇数的字符串首先排除; 2、注意检查括号vector是否空了。
4、实现
class Solution {
public:
bool isValid(string s) {
if(s.length() % 2 != 0)
return false;
vector <char> cv;
for(int i = 0; i < s.length(); i++){
if('(' == s[i] || '[' == s[i] || '{' == s[i]){
cv.push_back(s[i]);
}else {
if(')' == s[i]){
if(cv.size() > 0 && '(' == cv.back()){
cv.pop_back();
}else{
return false;
}
}else if(']' == s[i]){
if(cv.size() > 0 && '[' == cv.back()){
cv.pop_back();
}else{
return false;
}
}else if('}' == s[i]){
if(cv.size() > 0 && '{' == cv.back()){
cv.pop_back();
}else{
return false;
}
}else{
return false;
}
}
}
return cv.size() == 0 ? true : false;
}
};
5、反思
效果不错。