20. Valid Parentheses
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.
模拟栈操作
#include <iostream> #include <vector> #include <set> #include <algorithm> #include <string> #include <sstream> #include <cstring> #include <cmath> #include <stack> using namespace std; class Solution { public: bool isValid(string s) { if (s.size() == 1) { return false; } stack<char>sta; char ch; for (auto iter = s.begin(); iter != s.end(); iter++) { ch = *iter; if (ch == '(' || ch == '{' || ch == '[') { sta.push(ch); } else { if (sta.size() == 0) { return false; } ch = sta.top(); sta.pop(); switch (*iter) { case ')': if (ch != '(') { return false; } break; case '}': if (ch != '{') { return false; } break; case ']': if (ch != '[') { return false; } break; } } } if (sta.size() != 0) { return false; } return true; } }; int main() { Solution s; cout << s.isValid("[[)") << endl; return 0; }
Keep it simple!