【EASY】Valid Parentheses
发布于:2019-03-22 17:30,阅读数:444,点赞数:0
# 问题 原题链接:[https://leetcode.com/problems/valid-parentheses/](https://leetcode.com/problems/valid-parentheses/) Given a string containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: - Open brackets must be closed by the same type of brackets. - Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: ``` Input: "()" Output: true ``` Example 2: ``` Input: "()[]{}" Output: true ``` Example 3: ``` Input: "(]" Output: false ``` Example 4: ``` Input: "([)]" Output: false ``` Example 5: ``` Input: "{[]}" Output: true ``` # 分析过程 - 输入:一个只有括号的字符串 - 输出:是否合法 - 思路:使用一个栈,遍历字符串,遇到左括号就入栈,遇到右括号就判断栈顶是不是匹配的左括号,如果是就弹出,如果不是直接返回错误。遍历到最后如果是空栈则合法。 # 解决方法 ```swift class Solution { func isValid(_ s: String) -> Bool { var stack = Array<Character>() for c in s { if c == "(" || c == "[" || c == "{" { stack.append(c) } else { let left: Dictionary<Character, Character> = [ ")" : "(", "]" : "[", "}" : "{", ] guard stack.last != nil, stack.last == left[c] else { return false } stack.popLast() } } return stack.isEmpty } } ```
评论:0条