File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Question Link: https://leetcode.com/problems/word-pattern/
3
+ * Primary idea: Use two dictionarys to determine if a character is unique to a word
4
+ * Time Complexity: O(n), Space Complexity: O(n)
5
+ */
6
+
7
+ class WordPattern {
8
+ func wordPattern( pattern: String , _ str: String ) -> Bool {
9
+ var wordDict = [ String: Character] ( )
10
+ var charDict = [ Character: String] ( )
11
+ let strs = str. characters. split { $0 == " " } . map ( String . init)
12
+ let patterns = [ Character] ( pattern. characters)
13
+
14
+ guard patterns. count == strs. count else {
15
+ return false
16
+ }
17
+
18
+ for i in 0 ..< strs. count {
19
+ let currentWord = strs [ i]
20
+ let currentChar = patterns [ i]
21
+
22
+ if wordDict [ currentWord] == nil && charDict [ currentChar] == nil {
23
+ wordDict [ currentWord] = currentChar
24
+ charDict [ currentChar] = currentWord
25
+ } else {
26
+ if wordDict [ currentWord] != currentChar {
27
+ return false
28
+ }
29
+ }
30
+ }
31
+
32
+ return true
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments