【Python】力扣刷题之有效的括号,利用字符串替换解题,用栈解决

简介: 有效的括号,利用字符串替换解题,用栈解决

有效的括号

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

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

示例 1:

输入:s = "()"
输出:true
示例 2:

输入:s = "()[]{}"
输出:true
示例 3:

输入:s = "(]"
输出:false
示例 4:

输入:s = "([)]"
输出:false
示例 5:

输入:s = "{[]}"
输出:true

提示:

1 <= s.length <= 104
s 仅由括号 '()[]{}' 组成

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-parentheses

解题思路

有效的括号类型:
"()[]{}"或者 "{[]}"等可知如果属于有效的括号必定存在"()"或"[]"或"{}"。

对于 "()[]{}"

这一类的只需利用replace函数替换即可

s = s.replace("()","")
s = s.replace("[]","")
s = s.replace("{}","")

最终s=""

而对于 "{[]}"

这一类的就需要加上循环!

 while "()" in s or "[]" in s or "{}" in s:
            s = s.replace("()","")
            s = s.replace("[]","")
            s = s.replace("{}","")

只要是有效的括号最终s等于"".

返回值

return s==""

代码

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        while "()" in s or "[]" in s or "{}" in s:
            s = s.replace("()","")
            s = s.replace("[]","")
            s = s.replace("{}","")
        return s == ""

提交结果

在这里插入图片描述

java

class Solution {
    public boolean isValid(String s) {
        int length = s.length()/2;
        for(int i=0;i<length;i++){
            s = s.replace("()", "");
            s = s.replace("{}", "");
            s = s.replace("[]", "");
        }
        return s == "";

    }
}

在这里插入图片描述

解题思路

首先有效字符串的长度一定为偶数,因此如果字符串的长度为奇数,我们可以直接返回False,省去后续的遍历判断过程。

if len(s) % 2 == 1:
            return False

判断括号的有效性可以使用「栈」这一数据结构来解决。

为了快速判断括号的类型,我们可以使用字典存储每一种括号。字典的键为右括号,值为相同类型的左括号。

dic = {")":"(","}":"{","]":"["}

我们遍历给定的字符串 s。当我们遇到一个左括号时,如果是有效括号我们会在后续的遍历中,遇到一个相同类型的右括号,因此我们可以将这个左括号放入栈,这里的栈用列表。

stack = []

当我们遇到一个右括号时,我们需要将一个相同类型的左括号闭合。此时,我们可以取出栈顶的左括号并判断它们是否是相同类型的括号。如果不是相同的类型,或者栈中并没有左括号,那么字符串 s 无效,返回 False。

        
        for i in s:
            if stack and i in dic:
                if stack[-1] == dic[i]:
                    stack.pop()
                else:
                    return False
            else:
                stack.append(i)
            
        return not stack


if stack and i in dic:

表示遍历到右括号且栈不为空!

代码

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) % 2 == 1:
            return False
        dic = {")":"(","}":"{","]":"["}
        stack = []
        for i in s:
            if stack and i in dic:
                if stack[-1] == dic[i]:
                     stack.pop()
                else:
                     return False
            else:
                stack.append(i)
            
        return not stack

提交结果

在这里插入图片描述

目录
相关文章
|
12天前
|
存储 算法 调度
力扣中级算法(Python)
力扣中级算法(Python)
|
12天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
12天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
12天前
|
Python
刷题——Python篇(1)输入输出
刷题——Python篇(1)输入输出
|
12天前
|
算法 Python
力扣初级算法(Python)(二)
力扣初级算法(Python)(二)
|
12天前
|
Python
刷题——Python篇(3)字符串
刷题——Python篇(3)字符串
|
12天前
|
Python
刷题——Python篇(2)类型转换
刷题——Python篇(2)类型转换
|
12天前
|
机器学习/深度学习 存储 算法
刷题——Python篇(0)Hello World
刷题——Python篇(0)Hello World
|
12天前
|
算法 Python
力扣初级算法(Python)(一)
力扣初级算法(Python)(一)
|
13天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值