Given a list of strings words
and a string pattern
, return a list of words[i]
that match pattern
. You may return the answer in any order.
A word matches the pattern if there exists a permutation of letters p
so that after replacing every letter x
in the pattern with p(x)
, we get the desired word.
Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.
Example 1:
Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" Output: ["mee","aqq"] Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.
Example 2:
Input: words = ["a","b","c"], pattern = "a" Output: ["a","b","c"]
Constraints:
1 <= pattern.length <= 20
1 <= words.length <= 50
words[i].length == pattern.length
pattern
andwords[i]
are lowercase English letters.
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def match(s, t):
m1, m2 = [0] * 128, [0] * 128
for i in range(n):
if m1[ord(s[i])] != m2[ord(t[i])]:
return False
m1[ord(s[i])] = m2[ord(t[i])] = i + 1
return True
n = len(pattern)
return [word for word in words if match(word, pattern)]
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;
}
private boolean match(String s, String t) {
int[] m1 = new int[128];
int[] m2 = new int[128];
for (int i = 0; i < s.length(); ++i) {
char c1 = s.charAt(i);
char c2 = t.charAt(i);
if (m1[c1] != m2[c2]) {
return false;
}
m1[c1] = i + 1;
m2[c2] = i + 1;
}
return true;
}
}
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> ans;
for (auto& word : words)
if (match(word, pattern))
ans.push_back(word);
return ans;
}
bool match(string s, string t) {
vector<int> m1(128);
vector<int> m2(128);
for (int i = 0; i < s.size(); ++i)
{
if (m1[s[i]] != m2[t[i]]) return 0;
m1[s[i]] = i + 1;
m2[t[i]] = i + 1;
}
return 1;
}
};
func findAndReplacePattern(words []string, pattern string) []string {
match := func(s, t string) bool {
m1, m2 := make([]int, 128), make([]int, 128)
for i := 0; i < len(s); i++ {
if m1[s[i]] != m2[t[i]] {
return false
}
m1[s[i]] = i + 1
m2[t[i]] = i + 1
}
return true
}
var ans []string
for _, word := range words {
if match(word, pattern) {
ans = append(ans, word)
}
}
return ans
}