使用以下代码,我在控制台中获得fatal error: Can't form a Character from an empty String
。我不知道自己在哪里做错了什么。
class Solution {
func isValid(_ s: String) -> Bool {
var dictionary = [Character: Character]()
dictionary["("] = ")"
dictionary["{"] = "}"
dictionary["["] = "]"
for (i, character) in s.characters.enumerated() {
if i % 2 == 0 {
if let idx = s.index(s.startIndex, offsetBy: i + 1, limitedBy: s.endIndex) {
if dictionary[character] != s[idx] {
return false
}
}
}
}
return true
}
}
var sol = Solution()
let test = "()[]["
print(sol.isValid(test))
Xcode 8.3.2 Swift 3 +
答案 0 :(得分:1)
当s[idx]
太大时,问题来自idx
这个词。将idx
的计算更新为:
if let idx = s.index(s.startIndex, offsetBy: i + 1, limitedBy: s.index(s.endIndex, offsetBy: -1)) {
或者,正如Leo所建议的那样,
if let idx = s.index(s.startIndex, offsetBy: i + 1, limitedBy: s.index(before: s.endIndex)) {