Skip to content

Commit bcc9f92

Browse files
author
Yi Gu
committed
[String] add Solution to Word Pattern
1 parent aabbbd5 commit bcc9f92

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

String/WordPattern.swift

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
}

0 commit comments

Comments
 (0)