-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path890. Find and Replace Pattern
37 lines (29 loc) · 1.1 KB
/
890. Find and Replace Pattern
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
class Solution {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> result = new ArrayList<>();
for(String word:words){
if(matches(word,pattern)){
result.add(word);
}
}
return result;
}
private boolean matches(String word,String pattern){
char[] patternToWord = new char[26];
char[] wordToPattern = new char[26];
for(int index = 0; index<word.length(); index++){
char wordChar = word.charAt(index);
char patternChar = pattern.charAt(index);
if(patternToWord[patternChar-'a'] == 0){
patternToWord[patternChar-'a'] = wordChar;
}
if(wordToPattern[wordChar-'a'] == 0){
wordToPattern[wordChar-'a'] = patternChar;
}
if(patternToWord[patternChar-'a'] != wordChar || wordToPattern[wordChar-'a'] != patternChar){
return false;
}
}
return true;
}
}