一、题目
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.
二、思路
利用栈的特性检测括号是否匹配。
三、代码
class Solution {
public:
bool isValid(string s) {
int len = s.length();
stack<char> sk;
for(int i = 0 ;i < len;++i){
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
sk.push(s[i]);
else{
if(sk.empty()) return false;
if(sk.top() == '(' && s[i] == ')')
sk.pop();
else if(sk.top() == '[' && s[i] == ']')
sk.pop();
else if(sk.top() == '{' && s[i] == '}')
sk.pop();
else
return false;
}
}
return sk.empty();
}
};
232

被折叠的 条评论
为什么被折叠?



