20. 有效的括号 - 力扣(LeetCode)
解法:
class Solution {
public:bool isValid(string s) {unordered_map<char, char> m = {{')', '('}, {']','['}, {'}', '{'}};stack<char> stk;for (int i = 0; i < s.size(); ++i) {if (s[i] == '(' || s[i] == '[' || s[i] == '{') {stk.push(s[i]);}else {if (stk.empty() || m[s[i]] != stk.top()) {return false;}else {stk.pop();}}}return stk.empty(); }
};
总结:
计算时间复杂度O(N),空间复杂度O(N)(使用了stack)。