6.有效的括号-Valid Parentheses

LeetCode Link: https://leetcode.com/problems/valid-parentheses/

Description:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

An input string is valid if:
1.Open brackets must be closed by the same type of brackets.
2.Open brackets must be closed in the correct order.
有效字符串需满足:
1.左括号必须用相同类型的右括号闭合。
2.左括号必须以正确的顺序闭合。

Note that an empty string is also considered valid.
空字符串可被认为是有效字符串。

Example:

Input: "()"
Output: true

Input: "()[]{}"
Output: true

Input: "(]"
Output: false

Input: "([)]"
Output: false

Input: "{[]}"
Output: true

Tints:

  1. 个数是奇数个,一定无效。
  2. 后添加的左括号先闭合 "([{}])" ,也就是后添加的左括号会先遇到右括号,用一个stack来存放与左括号对应的右括号,后添加的右括号会被先删除掉。Last in first out。
  3. 在遍历字符串数组时,如果遇到一个左括号,就在stack里添加对应的右括号。如果遇到一个右括号,就将stack里的最后一个删掉,并对比最后一个与遇到的右括号是否相同。
  4. stack里的右括号的个数以及顺序都与左括号一一对应。根据stack是否为空判断是否有效。

Solution:

import Foundation

func isValid(_ s: String) -> Bool {
    
    if s.count % 2 != 0 { return false }
    
    let sArray = Array(s)  // 将字符串转成对应的数组。
    var stack = [String]() // 用一个数组stack来存放与左括号对应的右括号,
    
    for p in sArray {
        switch p {
        case "(": stack.append(")")
        case "[": stack.append("]")
        case "{": stack.append("}")
        default:
            if stack.isEmpty { return false }
            if let pop = stack.popLast(), pop != String(p) {
                return false
            }
        }
    }
    
    return stack.isEmpty
}

Runtime: 8 ms, faster than 82.68% of Swift online submissions for Valid Parentheses.

Memory Usage: 21.1 MB, less than 5.17% of Swift online submissions for Valid Parentheses.

Analyze:判断括号是否有效的实质:后添加的左括号先闭合 ,对应stack的数据结构

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容