首页 > 解决方案 > python中的空字符串问题

问题描述

我在解决 LeetCode 问题“20. 有效括号”

任务: 在此处输入图像描述

这是我的代码:

class Solution:
    def isValid(self, s: str) -> bool:
        
        values = {"()" : "", "{}" : "", "[]" : ""}
        
        
        def iteration(j):
            for key, value in values.items():
                k = j
                j = j.replace(key, f'{value}')
                
                if j != k:
                    return iteration(j)
                    
            if j == "":
                return True
            else:
                return False
            
        iteration(s)

输入是s = "{[]}"

所以,当我到达j =""它总是在行中失败if j == "":并返回 false 时,我不知道为什么。

标签: pythonstring

解决方案


您的代码返回“无”,您需要在函数 isValid 中返回:

class Solution:
    def isValid(self, s: str) -> bool:
        
        values = {"()" : "", "{}" : "", "[]" : ""}
        
        
        def iteration(j):
            for key, value in values.items():
                k = j
                j = j.replace(key, f'{value}')
                
                if j != k:
                    return iteration(j)
                    
            if j == "":
                return True
            else:
                return False
            
        return iteration(s) #This is my change add a return

推荐阅读