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) {
stack<char> tmp;
for(int i = 0; i < s.size(); ++i){
switch(s[i]){
case '(':
case '[':
case '{': tmp.push(s[i]);break;
case ')': if(tmp.empty() || tmp.top() != '(') return false;else tmp.pop();break;
case ']': if(tmp.empty() || tmp.top() != '[') return false;else tmp.pop();break;
case '}': if(tmp.empty() || tmp.top() != '{') return false;else tmp.pop();break;
default: ;
}
}
return tmp.empty();
}
};
本文介绍了一种使用栈数据结构来验证包含括号的字符串是否有效的算法。通过遍历字符串并利用栈来跟踪开闭括号的顺序,可以高效地判断括号是否正确配对。
270

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



