Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f68ebb6

Browse files
author
王俊超
committed
commit
1 parent 0879ca8 commit f68ebb6

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

.idea/modules.xml

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
/**
5+
* @author: wangjunchao(王俊超)
6+
* @time: 2018-10-10 17:24
7+
**/
8+
public class Solution {
9+
public boolean wordPattern(String pattern, String str) {
10+
11+
if (pattern == null && str == null) {
12+
return true;
13+
} else if (pattern == null || str == null) {
14+
return false;
15+
}
16+
17+
String[] parts = str.split("\\s+");
18+
19+
if (pattern.length() != parts.length) {
20+
return false;
21+
}
22+
23+
Map<Character, String> map = new HashMap<>();
24+
Map<String, Character> rmap = new HashMap<>();
25+
26+
Character c;
27+
for (int i = 0; i < pattern.length(); i++) {
28+
c = pattern.charAt(i);
29+
if (!map.containsKey(c)) {
30+
map.put(c, parts[i]);
31+
} else {
32+
if (!parts[i].equals(map.get(c))) {
33+
return false;
34+
}
35+
}
36+
// 双射,两边都要验证
37+
if (!rmap.containsKey(parts[i])) {
38+
rmap.put(parts[i], c);
39+
} else {
40+
if (!c.equals(rmap.get(parts[i]))) {
41+
return false;
42+
}
43+
}
44+
}
45+
46+
return true;
47+
}
48+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
* @author: wangjunchao(王俊超)
3+
* @time: 2018-10-10 17:29
4+
**/
5+
public class Test {
6+
public static void main(String[] args) {
7+
Solution solution = new Solution();
8+
9+
System.out.println(solution.wordPattern("abba", "dog cat cat dog"));
10+
System.out.println(solution.wordPattern("abba", "dog cat cat fish"));
11+
System.out.println(solution.wordPattern("aaaa", "dog cat cat dog"));
12+
System.out.println(solution.wordPattern("abba", "dog dog dog dog"));
13+
}
14+
}

0 commit comments

Comments
 (0)