0

With the following code, I get fatal error: Can't form a Character from an empty String in the Console. I don't see where or what I'm doing wrong.

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+

Daniel
  • 158
  • 1
  • 14
  • Compare http://stackoverflow.com/q/42958011/2976878 – the `limitedBy:` parameter is an *inclusive* upper bound, so you're trying to subscript the string with its `endIndex` (which is a past the end index). – Hamish May 18 '17 at 23:30

1 Answers1

1

The problem is from the expression s[idx] when idx is too large. The error goes away when you update the calculation of idx to:

if let idx = s.index(s.startIndex, offsetBy: i + 1, limitedBy: s.index(s.endIndex, offsetBy: -1)) {

or, as kindly suggested by Leo,

if let idx = s.index(s.startIndex, offsetBy: i + 1, limitedBy: s.index(before: s.endIndex)) {
rmaddy
  • 314,917
  • 42
  • 532
  • 579