python - 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 时,我不知道为什么。
解决方案
您的代码返回“无”,您需要在函数 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
推荐阅读
- ruby-on-rails - 在控制台中使用箭头键时 UTF-8 中的无效字节序列 (ArgumentError)
- c++ - 如何使用指针访问矩阵列的元素
- react-native - React Native 在后台推送本地通知(已终止)
- c# - 无论操作系统如何,如何获取特定的 TimeZoneInfo?
- python - 从文本文件的最后一行删除一个新行
- android - RecyclerView 和 AdapterHelper 中的 Android ANR
- bash - 读取 CSV 并使用条件添加数据
- python - 使用某些窗口节能选项可以冻结 python 代码工作吗?
- json - 使用 Windows Powershell 命令批量更新 JSON 文件
- reactjs - React JSX 与变量中的组件不同步道具