[leetcode]39 Valid Parentheses
3513 ワード
タイトルリンク: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、実現
5、反省
効果はいいですね.
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、反省
効果はいいですね.