-
Notifications
You must be signed in to change notification settings - Fork 17
/
WordPattern.java
66 lines (48 loc) · 1.54 KB
/
WordPattern.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class GfG {
// M - I
public static ArrayList<String> findMatchedWords(ArrayList<String> dict, String pattern) {
ArrayList<String> res = new ArrayList<>();
int len = pattern.length();
for(String str: dict) {
if(check(str, pattern)) res.add(str);
}
return res;
}
static boolean check(String word, String pattern) {
int len = pattern.length();
if(word.length() != len) return false;
char arr[] = new char [128];
for(int i=0; i<len; i++) {
if(arr[(int)pattern.charAt(i)] == 0) {
arr[(int)pattern.charAt(i)] = word.charAt(i);
} else if(arr[(int)pattern.charAt(i)] != word.charAt(i)) {
return false;
}
}
return true;
}
// M - II
public static ArrayList<String> findMatchedWords(ArrayList<String> dict, String pattern) {
ArrayList<String> res = new ArrayList<>();
int len = pattern.length();
String hash = encode(pattern);
for(String str: dict) {
if(str.length() == len && encode(str).equals(hash)) res.add(str);
}
return res;
}
static String encode(String str) {
int counter=1;
String res = "";
HashMap<Character, Integer> map= new HashMap<>();
for(int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if(!map.containsKey(c)) {
map.put(c, counter);
counter++;
}
res += map.get(c);
}
return res;
}
}