LeetCode Solutions
890. Find and Replace Pattern
Time: Space:
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> ans;
for (const string& word : words)
if (isIsomorphic(word, pattern))
ans.push_back(word);
return ans;
}
private:
bool isIsomorphic(const string& w, const string& p) {
vector<int> map_w(128);
vector<int> map_p(128);
for (int i = 0; i < w.length(); ++i) {
if (map_w[w[i]] != map_p[p[i]])
return false;
map_w[w[i]] = i + 1;
map_p[p[i]] = i + 1;
}
return true;
}
};
class Solution {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> ans = new ArrayList<>();
for (final String word : words)
if (isIsomorphic(word, pattern))
ans.add(word);
return ans;
}
private boolean isIsomorphic(final String w, final String p) {
Map<Character, Integer> map_w = new HashMap<>();
Map<Character, Integer> map_p = new HashMap<>();
for (Integer i = 0; i < w.length(); ++i)
if (map_w.put(w.charAt(i), i) != map_p.put(p.charAt(i), i))
return false;
return true;
}
}
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def isIsomorphic(w: str, p: str) -> bool:
return [*map(w.index, w)] == [*map(p.index, p)]
return [word for word in words if isIsomorphic(word, pattern)]