本题题目要求如下:
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) {
for (int i = 0; i < s.length(); ++i) {
if (parenMap.find(s[i]) != parenMap.end()) {
myStack.push(s[i]);
}
else {
if (myStack.empty() or parenMap[myStack.top()] != s[i]) {
return false;
}
myStack.pop();
}
}
if (!myStack.empty()) {
return false;
}
return true;
}
private:
stack<char> myStack;
unordered_map<char, char> parenMap = {
{'(', ')'},
{'[', ']'},
{'{', '}'}};
};