Find and Replace Pattern
July 27, 2020
Find and Replace Pattern
class Solution {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> result = new ArrayList<>();
String patternToNum = changeToNum(pattern);
for (String word : words) {
String wordToNum = changeToNum(word);
if (wordToNum.equals(patternToNum)) {
result.add(word);
}
}
return result;
}
public String changeToNum(String word) {
Map<Character, Integer> mapping = new HashMap<>();
char[] array = word.toCharArray();
int index = 0;
String patternToNum = null;
for (char c : array) {
if (mapping.get(c) == null) {
mapping.put(c, index);
index++;
}
patternToNum = patternToNum + mapping.get(c);
}
return patternToNum;
}
}