Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit 909e0f1

Browse files
committed
290. Word Pattern
1 parent 7051a28 commit 909e0f1

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

290. Word Pattern.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# 290. Word Pattern
2+
3+
### 2017-03-13
4+
5+
Given a `pattern` and a string `str`, find if `str` follows the same pattern.
6+
7+
Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `str`.
8+
9+
**Examples:**
10+
11+
1. pattern = `"abba"`, str = `"dog cat cat dog"` should return true.
12+
2. pattern = `"abba"`, str = `"dog cat cat fish"` should return false.
13+
3. pattern = `"aaaa"`, str = `"dog cat cat dog"` should return false.
14+
4. pattern = `"abba"`, str = `"dog dog dog dog"` should return false.
15+
16+
**Notes:**
17+
You may assume `pattern` contains only lowercase letters, and `str` contains lowercase letters separated by a single space.
18+
19+
20+
21+
# Solution
22+
23+
```swift
24+
class Solution {
25+
func wordPattern(_ pattern: String, _ str: String) -> Bool {
26+
let array = str.components(separatedBy: " ")
27+
guard pattern.characters.count == array.count else { return false }
28+
var dict = [String: String]()
29+
for (i, char) in pattern.characters.enumerated() {
30+
let word = array[i]
31+
let c = char.description
32+
if let test = dict[c] {
33+
guard test == word else { return false }
34+
} else {
35+
if dict.values.contains(word) {
36+
return false
37+
} else {
38+
dict[c] = word
39+
}
40+
}
41+
}
42+
return true
43+
44+
}
45+
}
46+
```
47+

0 commit comments

Comments
 (0)