当前位置:网站首页>20. 有效的括号

20. 有效的括号

2022-06-11 08:55:00 拽拽就是我

leetcode力扣刷题打卡

题目:20. 有效的括号
描述:给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

解题思路

1、遇见括号问题,基本就是栈解决;
2、栈为空,直接push进来;栈不为空,就比较栈顶元素和新元素是否配对,配对就直接出栈;
3、最后判断栈是否为空,全部都配对了栈肯定为空,返回true,反之返回false;

原代码##

class Solution {
    
public:
    bool ispair(char a, char b) {
    
        switch (a) {
    
            case '(':
                if (b == ')') return true;
                else return false;
            case '{':
                if (b == '}') return true;
                else return false;
            case '[':
                if (b == ']') return true;
                else return false;
            default:
                return false;
        }
    }
    bool isValid(string s) {
    
        stack<char>sc;
        for (int i = 0; i < s.size(); ++i) {
    
            if (sc.empty()) {
    
                sc.push(s[i]);
                continue;
            } else {
    
                char temp = sc.top();
                if (ispair(temp, s[i])) sc.pop(); 
                else sc.push(s[i]);
            }
            
        }
        if (sc.empty()) return true;
        else return false;    
    }  
};
原网站

版权声明
本文为[拽拽就是我]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_32355021/article/details/125137899