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!