0

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples: pattern = "abba", str = "dog cat cat dog" should return true.

pattern = "abba", str = "dog cat cat fish" should return false.

pattern = "aaaa", str = "dog cat cat dog" should return false.

pattern = "abba", str = "dog dog dog dog" should return false.

Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

class Solution
{
    func wordPattern(pattern: String, _ str: String) -> Bool
    {

        let arr = str.characters.split{$0 == " "}.map(String.init)
        if arr.count != pattern.characters.count
        {
            return false
        }

        var dict = [Character:String]()

        for i in (0...arr.count-1)
        {
            let cha = pattern[pattern.startIndex.advancedBy(i)]

            if dict.keys.contains(cha)
            {
                if dict[cha]! != arr[i]
                {
                    return false
                }
            }
            else
            {
                if dict.values.contains(dict[cha]!)
                //fatal error: unexpectedly found nil while unwrapping an Optional value
                {
                    return false
                }

                dict[cha] = arr[i]
            }

        }
        return true
    }
}


var test = Solution()
var result = test.wordPattern("abba", "dog cat cat dog")
print(result)

I do not know "fatal error: unexpectedly found nil while unwrapping an Optional value". Any help, I appreciate it. Thank you so much!

Sulthan
  • 128,090
  • 22
  • 218
  • 270
Tang
  • 351
  • 1
  • 4
  • 15
  • I do not know what your question mean? Do you have any idea how to fix it? Thanks a lot! – Tang Jun 11 '16 at 18:48

1 Answers1

1

Revise your conditions.

Your else branch is executed when dict.keys.contains(cha) is false, in other words, when the dictionary does not contain cha. You then try to access dict[cha] which you already know must return nil (because cha is not in the dictionary). And then you try to unwrap it. Unwrapping nil crashes your app.

Also consider that the condition is trying to check whether a value taken from the dictionary is contained in the dictionary. What are you trying to do?

All you want is probably just (note there are no nasty !):

let arrayValue = arr[i]

if let value = dict[cha] {
    if value != arrayValue {
        return false
    }
} else {
    if dict.values.contains(arrayValue) { // maybe this? it's hard to guess
        return false
    }

    dict[cha] = arrayValue
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270