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.
Personal Tips:利用map匹配括号对,利用栈弹出,然后通过操作数判断是否全部遍历,代码如下:
class Solution {
public:
Solution()
{
temp.insert(pair<char, char>('(', ')'));
temp.insert(pair<char, char>('{', '}'));
temp.insert(pair<char, char>('[', ']'));
}
bool isValid(string s) {
vector<char> stack;
int i = 0; int count = 0;
while (s[i]!='\0')
{
if (s[i] == '(' || s[i] == '{' || s[i] == '[')
{
stack.push_back(s[i]); count++;
}
if (stack.empty()) return false;
if (s[i] == temp[stack.back()])
{
stack.pop_back(); count++;
}
++i;
}
return (stack.empty()&&count==s.size());
}
private:
map<char, char> temp;
};
本文介绍了一种使用栈和映射表来验证字符串中括号是否正确配对的方法。该方法适用于包含圆括号、方括号及花括号的字符串。通过C++实现了一个Solution类,其中isValid函数用于检查输入字符串的括号是否有效。
2045

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



