首页 > 其他 > 详细

leetcood学习笔记-20

时间:2019-03-10 14:26:01      阅读:140      评论:0      收藏:0      [点我收藏+]
 

学习内容:

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 == ‘‘

 

leetcood学习笔记-20

原文:https://www.cnblogs.com/oldby/p/10505224.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!