Skip to content

Commit 4dbf5c8

Browse files
committed
add solution of problem 290: word pattern
1 parent 2f3fac6 commit 4dbf5c8

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

WordPattern290/README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
Given a `pattern` and a string `str`, find if `str` follows the same pattern.
2+
3+
Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `str`.
4+
5+
#####Examples:
6+
1. pattern = "abba", str = "dog cat cat dog" should return true.
7+
2. pattern = "abba", str = "dog cat cat fish" should return false.
8+
3. pattern = "aaaa", str = "dog cat cat dog" should return false.
9+
4. pattern = "abba", str = "dog dog dog dog" should return false.
10+
#####Notes:
11+
You may assume `pattern` contains only lowercase letters, and `str` contains lowercase letters separated by a single space.

WordPattern290/Solution.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
public class Solution {
2+
public boolean wordPattern(String pattern, String str) {
3+
if (pattern == null || str == null)
4+
return false;
5+
6+
String[] strs = str.split(" ");
7+
8+
if (pattern.length() != strs.length) {
9+
return false;
10+
} else {
11+
Map<String, Character> map1 = new HashMap<String, Character>();
12+
Map<Character, String> map2 = new HashMap<Character, String>();
13+
14+
for (int i = 0; i < pattern.length(); i++) {
15+
if (!map1.containsKey(strs[i]) && !map2.containsKey(pattern.charAt(i))) {
16+
map1.put(strs[i], pattern.charAt(i));
17+
map2.put(pattern.charAt(i), strs[i]);
18+
} else if (!map1.containsKey(strs[i]) || map1.get(strs[i]) != pattern.charAt(i)) {
19+
return false;
20+
} else if (!map2.containsKey(pattern.charAt(i)) || !strs[i].equals(map2.get(pattern.charAt(i)))) {
21+
return false;
22+
}
23+
}
24+
25+
return true;
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)