题目链接
leetcode
题目描述
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。
有效字符串需满足:
1 2 3
| 1. 左括号必须用相同类型的右括号闭合。 2. 左括号必须以正确的顺序闭合。 3. 每个右括号都有一个对应的相同类型的左括号。
|
C++ 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #include <iostream> #include <stack> #include <vector> using namespace std;
class Solution { public: bool isValid(string s) { stack<int> stk; for (const char& c : s) { if (c == '(' || c == '{' || c == '[') { stk.push(c); } else if (c == ')' || c== '}' || c == ']') { if (stk.empty() || stk.top() != getLeft(c)) { return false; } stk.pop(); } }
return stk.empty(); }
char getLeft(char c) { if (c == ')') return '('; else if (c == '}') return '{'; else if (c == ']') return '['; return ' '; } };
int main() { Solution solution; vector<string> s_cases = { "()", "()[]{}", "(]", "([])" };
for (const string& s : s_cases) { bool result = solution.isValid(s);
cout << "Input: \"" << s << "\"\n"; cout << "Output: " << (result ? "true" : "false") << "\n"; }
return 0; }
|