★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝()➤GitHub地址:➤原文地址: ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"输出: true
示例 2:
输入: "()[]{}"输出: true
示例 3:
输入: "(]"输出: false
示例 4:
输入: "([)]"输出: false
示例 5:
输入: "{[]}"输出: true
1 class Solution { 2 func isValid(_ s: String) -> Bool { 3 //字符串为空返回true 4 if s.isEmpty 5 { 6 return true 7 } 8 else 9 {10 //或字符串的字符个数为奇数个直接排除11 if s.count%2==112 {13 return false14 }15 }16 //创建字典对照表17 var map:[Character:Character]=[")":"(","}":"{","]":"["]18 //偶数符串若第一个字符就是右边的符号则直接排除19 if map[s[s.startIndex]] != nil20 {21 return false22 }23 //创建字符串堆栈24 var stackOfString=Stack()25 //遍历字符串26 for char in s27 {28 //为右侧符号,且查询字典对应堆栈中最后一个元素29 if map[char] != nil && map[char]==stackOfString.GetLastElement()30 {31 //出栈32 stackOfString.pop()33 }34 else35 {36 //入栈37 stackOfString.push(char)38 }39 }40 return stackOfString.count()==041 }42 //堆栈的泛型通用版本43 struct Stack {44 var items = [Element]()45 //入栈46 //mutating 关键字修饰方法是为了能在该方法中修改 struct 或是 enum 的变量47 mutating func push(_ item: Element) {48 items.append(item)49 }50 //出栈51 mutating func pop() -> Element {52 return items.removeLast()53 }54 //返回堆栈中的元素个数55 mutating func count()->Int56 {57 return items.count58 }59 //获取最后一个元素60 mutating func GetLastElement()->Element61 {62 return items[items.count-1]63 }64 }65 }
高效率版
1 class Solution { 2 func isValid(_ s: String) -> Bool { 3 var opened = "" 4 for char in s { 5 if char == "(" { 6 opened += ")" 7 } else if char == "{" { 8 opened += "}" 9 } else if char == "[" {10 opened += "]"11 } else {12 if let prevVal = opened.last, prevVal == char {13 opened.removeLast()14 } else {15 return false16 }17 }18 }19 return opened.isEmpty20 }21 }