-
Notifications
You must be signed in to change notification settings - Fork 886
/
WordPattern.swift
35 lines (29 loc) · 1007 Bytes
/
WordPattern.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Question Link: https://leetcode.com/problems/word-pattern/
* Primary idea: Use two dictionarys to determine if a character is unique to a word
* Time Complexity: O(n), Space Complexity: O(n)
*/
class WordPattern {
func wordPattern(_ pattern: String, _ str: String) -> Bool {
let strs = str.split(separator: " ").map(String.init)
guard pattern.count == strs.count else {
return false
}
var patternToWord = [Character: String]()
for (i, char) in pattern.enumerated() {
let word = strs[i]
if let charWord = patternToWord[char] {
if charWord != word {
return false
}
} else {
if patternToWord.values.contains(word) {
return false
} else {
patternToWord[char] = word
}
}
}
return true
}
}