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;
};