-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path890. Find and Replace Pattern.java
47 lines (47 loc) · 1.82 KB
/
890. Find and Replace Pattern.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
class Solution {
public List<String> findAndReplacePattern(String[] words, String pattern) {
/*
* Question is fairly easy to solve
* Think that way.
* First generate and number pattern using hasmap.put(key, index++)
* iterate all words and generate patternforcurrent word
* and just compare using
* patternWordPermutation.equals(currwordPattern)
*/
List<String> foundWords = new ArrayList<>();
String patternPermutationString = this.generatePermutationString(pattern);
// cheeck locally
System.out.println(patternPermutationString);
// iterate over all words
for(String word : words) {
if (word.length() == pattern.length()) {
String currentWordPermutation = this.generatePermutationString(word);
if (patternPermutationString.equals(currentWordPermutation)==true) {
foundWords.add(word);
}
}
}
return foundWords;
}
private String generatePermutationString(String pattern) {
HashMap<Character, Integer> hashMap = new HashMap<>();
int index = 0;
StringBuilder permutationString = new StringBuilder();
for (int i = 0; i < pattern.length(); i++) {
char key = pattern.charAt(i);
if (hashMap.containsKey(key) == false) {
index++;
hashMap.put(key, index);
}
permutationString.append(hashMap.get(key));
}
return permutationString.toString();
}
}