swfit 6. The algorithm is simple and effective brackets

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/huanglinxiao/article/details/91453161

Includes only a given '(', ')' string, '{', '}', '[', ']', and determine whether the string is valid.

Valid string must meet:

Left bracket must be closed by a closing parenthesis of the same type.
Left parenthesis must be closed in the correct order.
Note the empty string can be considered a valid string.

Example 1:

Input: "()"
Output: true
Example 2:

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

Input: "(]"
Output: false

solution:

  func isValid(_ s: String) -> Bool {
        var stack = [Character]()
        
        for char in s {
            if char == "(" || char == "[" || char == "{" {
                stack.append(char)
            } else if char == ")" {
                guard stack.count != 0 && stack.removeLast() == "(" else {
                    return false
                }
            } else if char == "]" {
                guard stack.count != 0 && stack.removeLast() == "[" else {
                    return false
                }
            } else if char == "}" {
                guard stack.count != 0 && stack.removeLast() == "{" else {
                    return false
                }
            }
        }
        
        return stack.isEmpty
    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/91453161