[swift] LeetCode 20. Valid Parentheses

栏目: Swift · 发布时间: 7年前

内容简介:Total Accepted: 103858 Total Submissions: 355021 Difficulty: EasyGiven a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.The brackets must close in the correct order, “()” and “()[]{}” are all

Total Accepted: 103858 Total Submissions: 355021 Difficulty: Easy

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

Subscribe to see which companies asked this question

func isValid(_ s: String) -> Bool {
    var stack = [Character](), b = true
 
    func compare(_ c: Character) -> Bool {
        guard let t = stack.popLast()  else { return false }
        return (c == ")" && t == "(") || (c == "]" && t == "[" ) || (c == "}" && t == "{")
    }
 
    loop: for c in s {
        switch c {
        case "(", "[", "{":
            stack.append(c)
        default:
            b = compare(c)
            if !b { break loop }
        }
    }
    
    return b && stack.isEmpty
}
[swift] LeetCode 20. Valid Parentheses [swift] LeetCode 20. Valid Parentheses

(随着网站访问量的激增,服务器配置只得一再升级以维持网站不“404 Not Found”,所以网站的维护费用也在不断上涨……(目前的阿里云服务器ECS+云数据库RDS+域名购买+七牛云的费用是2200元/年),为了能不放弃该网站,所以我又把打赏链接放上来啦~所有打赏金额都会被记账并投入博客维护中,感谢厚爱,多多关照~)


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

写给大家看的算法书

写给大家看的算法书

【日】杉浦 贤 / 绝云 / 电子工业出版社 / 2016-6 / 59.00元

算法这个词对于非计算机从业人士而言,似乎就是晦涩、神秘的代名词。其实,算法在日常生活中随处可见。做饭用的菜谱是一种算法、查字典的方法是一种算法、给期中考试分数排名也用到了算法。事实上,算法可以说是这个信息爆炸的时代所依存的重要基石之一。 《写给大家看的算法书》对于理解信息处理的基础——算法而言,是一本非常优秀的入门读物。作者采用大量生动的类比,配合简洁易懂的配图,深入浅出地讲解算法,极大地拉......一起来看看 《写给大家看的算法书》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具