Skip to content

Commit 6f9dd83

Browse files
authored
Create 890. Find and Replace Pattern
1 parent b6d7fb6 commit 6f9dd83

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

890. Find and Replace Pattern

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public List<String> findAndReplacePattern(String[] words, String pattern) {
3+
List<String> result = new ArrayList<>();
4+
5+
for(String word:words){
6+
if(matches(word,pattern)){
7+
result.add(word);
8+
}
9+
}
10+
11+
return result;
12+
}
13+
14+
private boolean matches(String word,String pattern){
15+
char[] patternToWord = new char[26];
16+
char[] wordToPattern = new char[26];
17+
18+
for(int index = 0; index<word.length(); index++){
19+
char wordChar = word.charAt(index);
20+
char patternChar = pattern.charAt(index);
21+
22+
if(patternToWord[patternChar-'a'] == 0){
23+
patternToWord[patternChar-'a'] = wordChar;
24+
}
25+
26+
if(wordToPattern[wordChar-'a'] == 0){
27+
wordToPattern[wordChar-'a'] = patternChar;
28+
}
29+
30+
if(patternToWord[patternChar-'a'] != wordChar || wordToPattern[wordChar-'a'] != patternChar){
31+
return false;
32+
}
33+
}
34+
35+
return true;
36+
}
37+
}

0 commit comments

Comments
 (0)