-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.swift
More file actions
29 lines (25 loc) · 854 Bytes
/
Solution.swift
File metadata and controls
29 lines (25 loc) · 854 Bytes
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
/*
Word Pattern
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.
*/
import Foundation
func wordPattern(_ pattern: String, _ str: String) -> Bool {
let words = str.components(separatedBy: " ")
if words.count != pattern.count {
return false
}
var mapping = Dictionary<Character, String>()
var backwardsMapping = Dictionary<String, Character>()
for (ch, word) in zip(pattern, words) {
if mapping[ch] == nil && backwardsMapping[word] == nil {
mapping[ch] = word
backwardsMapping[word] = ch
} else {
if mapping[ch] != word {
return false
}
}
}
return true
}