python字符串与列表的相互转换
学习内容:
1.字符串转列表
2.列表转字符串
1. 字符串转列表
str1 = "hi hello world" print(str1.split(" "))
输出:
['hi', 'hello', 'world']
2. 列表转字符串
l = ["hi","hello","world"] print(" ".join(l))
输出:
hi hello world
题目描述:
第一次提交:
class Solution: def isValid(self, s: str) -> bool: dic = {"(": ")", "{": "}", "[": "]",} l = [] for i in range(len(s)): if s[i] in dic:#此处在字典中的是左括号! l.append(s[i]) else: if len(l)==0: return False elif dic[l.pop()]!=s[i]: return False if l==[]: return True else: return False
优化后的:
class Solution: def isValid(self, s: str) -> bool: dic = {"(": ")", "{": "}", "[": "]",} l = [] for i in s: if i in dic: l.append(i) elif len(l)==0 or dic[l.pop()]!=i: return False return not l
方法二
class Solution: def isValid(self, s): while '{}' in s or '()' in s or '[]' in s: s = s.replace('{}', '') s = s.replace('[]', '') s = s.replace('()', '') return s == ''
学习内容:
1.字符串转列表
2.列表转字符串
1. 字符串转列表
str1 = "hi hello world" print(str1.split(" "))
输出:
['hi', 'hello', 'world']
2. 列表转字符串
l = ["hi","hello","world"] print(" ".join(l))
输出:
hi hello world
题目描述:
第一次提交:
class Solution: def isValid(self, s: str) -> bool: dic = {"(": ")", "{": "}", "[": "]",} l = [] for i in range(len(s)): if s[i] in dic:#此处在字典中的是左括号! l.append(s[i]) else: if len(l)==0: return False elif dic[l.pop()]!=s[i]: return False if l==[]: return True else: return False
优化后的:
class Solution: def isValid(self, s: str) -> bool: dic = {"(": ")", "{": "}", "[": "]",} l = [] for i in s: if i in dic: l.append(i) elif len(l)==0 or dic[l.pop()]!=i: return False return not l
方法二
class Solution: def isValid(self, s): while '{}' in s or '()' in s or '[]' in s: s = s.replace('{}', '') s = s.replace('[]', '') s = s.replace('()', '') return s == ''