题目
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’?的字符串 s ,判断字符串是否有效。
有效字符串需满足:
1. 左括号必须用相同类型的右括号闭合。
2. 左括号必须以正确的顺序闭合。
算法实现
func isValid(_ s: String) -> Bool {
let pairMap = ["(": ")", "{": "}", "[": "]"] as [Character: Character]
var stack = [Character]()
for character in s {
if pairMap.keys.contains(character) {
stack.append(character)
} else {
guard let key = stack.last else {
return false
}
if pairMap[key] == character {
stack.popLast()
} else {
return false
}
}
}
return stack.isEmpty
}
注意点
- Swift中Character类型;
- as关键字的运用;
|