LeetCode题解——有效的括号

LeetCode题解——有效的括号

  • 题目介绍

LeetCode题解——有效的括号_第1张图片

  • 解题思路
  1. 这题可以从两个角度来考虑,首先第一种寻找删除,在字符串里面查找成对出现的括号,然后用空格替换,最后检查字符串是不是为空
  2. 第二种,好比消消乐一样,当正确的配对括号就删除,首先我们创建一个栈,然后遍历字符串
  3. 当第一次栈为空,直接将元素字符入栈,然后接下来每次的字符和栈首对比,如果是配对括号,就将栈首出栈,否则入栈,遍历完字符串后,通过查看栈是否为空
  4. 第二种比第一种的时间复杂度要好点,但是多了一个栈的空间,相当于空间换时间
  • 代码示例

第一种:

class Solution {
public:
    bool isValid(string s) {
        vector sdict = {"()","[]","{}"};
        while(s.empty() != true) {
            int flag =0;
            for(auto &x:sdict) {
                int index = s.find(x,0);
                if(index < 0 ){
                    continue;
                }
                s.replace(index,2,"");
                flag++;
            }
            if(0 == flag) {    //这个标志很重要,判断字符串里面是否还有成对的括号
                break;
            }
        }
        if(s.empty() != true) {
            return false;
        }else{
            return true;
        }
    }
};

第二种:

class Solution {
public:
    bool isValid(string s) {
        map mdict = {{'(',')'},{'[',']'},{'{','}'}};
        stack res;
        for(auto &x:s){
            if(res.empty() == true){
                res.push(x);
            }else{
                if(mdict[res.top()] == x) {
                    res.pop();
                }else{
                    res.push(x);
                }
            }
        }
        if(res.empty() != true) {
            return false;
        }else{
            return true;
        }
    }
};

 

你可能感兴趣的:(算法,leetcode,栈)