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.
思路:利用堆栈。
当'(' '[' '{' 出现时让他们入堆栈,当')' ']' '}'出现时,取栈顶元素看是否与其匹配,若匹配出栈,不匹配返回false。
最后如果栈元素为零,则括号匹配。
特别注意当栈元素为零时,不要再执行出栈操作,直接返回false。
class Solution {
public:
bool isValid(string s) {
if(s.size()==0)
return false;
stack<char> stk;
for(int i=0;i<s.size();++i){
if(s[i]=='{'||s[i]=='['||s[i]=='(')
stk.push(s[i]);
if(s[i]=='}'||s[i]==']'||s[i]==')'){
if(stk.size()==0)
return false;
if((s[i]==')'&&stk.top()!='(')||(s[i]=='}'&&stk.top()!='{')||(s[i]==']'&&stk.top()!='['))
return false;
stk.pop();
}
}
if(stk.size()==0)
return true;
}
};
本文介绍了一种使用堆栈数据结构来验证字符串中括号是否正确配对的方法。具体实现包括处理圆括号、方括号及花括号,并通过LeetCode上的经典题目进行实践。
910

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



