leetcode 290. Word Pattern


  1. Word Pattern:题目链接

方法1:HashMap

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
30
31
32
33
import java.util.HashMap;
import java.util.Map;

public class Solution1 {
public boolean wordPattern(String pattern, String str) {
Map<Character, String> map = new HashMap<>();
String[] res = str.split(" ");

if (pattern.length() != res.length){
return false;
}
for (int i=0;i<pattern.length();++i) {
if (map.containsKey(pattern.charAt(i))){
if (!map.get(pattern.charAt(i)).equals(res[i])) {
return false;
}
}else{
if (map.containsValue(res[i])){
return false;
}
map.put(pattern.charAt(i), res[i]);
}
}
return true;

}

public static void main(String[] args) {
String pattern = "abba";
String str = "dog cat cat dog";
System.out.println(new Solution1().wordPattern(pattern, str));
}
}

pS: 源代码链接

文章目录
  1. 1. 方法1:HashMap
|