时间复杂度O(n):遍历所有元素
    空间复杂度O(n):括号都不匹配的情况下,所有元素都要同时入栈。

    1. class Solution {
    2. public:
    3. /**
    4. *
    5. * @param s string字符串
    6. * @return bool布尔型
    7. */
    8. bool isValid(string s) {
    9. // write code here
    10. // 建立左右括号对应的哈系表
    11. unordered_map<char, char> mp{{'{', '}'}, {'[', ']'}, {'(', ')'}};
    12. stack<int> st;
    13. // 遍历括号序列中的括号
    14. for (char c : s) {
    15. // 如果是右括号且栈顶元素是哈系表中对应的左括号时,出栈
    16. // 栈为空说明存在多余右括号
    17. // 不匹配说明左右括号不匹配
    18. if (!st.empty() && mp[st.top()] == c) st.pop();
    19. // 其它情况元素入栈
    20. else st.push(c);
    21. }
    22. // 最后判断栈是否为空,如果不为空说明存在多余左括号
    23. return st.empty();
    24. }
    25. };
    1. class Solution {
    2. public:
    3. /**
    4. *
    5. * @param s string字符串
    6. * @return bool布尔型
    7. */
    8. bool isValid(string s) {
    9. // write code here
    10. // 括号序列不合法的三种情况
    11. // 1. 左右括号不匹配
    12. // 2. 存在多余的左括号
    13. // 3. 存在多余的右括号
    14. stack<int> st;
    15. // 遍历括号序列中的括号
    16. for (char c : s) {
    17. // 当遇到左括号时入栈相对应的右括号
    18. if (c == '{') st.push('}');
    19. else if (c == '[') st.push(']');
    20. else if (c == '(') st.push(')');
    21. // 当遇到右括号时,判断是否与此时栈顶元素相同
    22. // 如果相同则出栈,不相同说明序列中存在左右不匹配的括号
    23. // 如果此时栈为空说明存在多余的右括号
    24. else if (st.empty() || st.top() != c) return false;
    25. else st.pop();
    26. }
    27. // 遍历完成后若栈不为空,说明存在多余的左括号
    28. return st.empty();
    29. }
    30. };