Created
May 21, 2021 07:41
-
-
Save vrat28/c262a5b55e977cf51833cd212c096ae6 to your computer and use it in GitHub Desktop.
Find and Replace(Java)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public List<String> findAndReplacePattern(String[] words, String pattern) { | |
List<String> ans = new ArrayList(); | |
for (String word: words) | |
if (match(word, pattern)) | |
ans.add(word); | |
return ans; | |
} | |
public boolean match(String word, String pattern) { | |
Map<Character, Character> m1 = new HashMap(); | |
Map<Character, Character> m2 = new HashMap(); | |
for (int i = 0; i < word.length(); ++i) { | |
char w = word.charAt(i); | |
char p = pattern.charAt(i); | |
if (!m1.containsKey(w)) m1.put(w, p); | |
if (!m2.containsKey(p)) m2.put(p, w); | |
if (m1.get(w) != p || m2.get(p) != w) | |
return false; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment