你有一个单词列表 words
和一个模式 pattern
,你想知道 words
中的哪些单词与模式匹配。
如果存在字母的排列 p
,使得将模式中的每个字母 x
替换为 p(x)
之后,我们就得到了所需的单词,那么单词与模式是匹配的。
(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。)
返回 words
中与给定模式匹配的单词列表。
你可以按任何顺序返回答案。
示例:
输入:words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
输出:["mee","aqq"]
解释:
"mee" 与模式匹配,因为存在排列 {a -> m, b -> e, ...}。
"ccc" 与模式不匹配,因为 {a -> c, b -> c, ...} 不是排列。
因为 a 和 b 映射到同一个字母。
提示:
1 <= words.length <= 50
1 <= pattern.length = words[i].length <= 20
C
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
char** findAndReplacePattern(char** words, int wordsSize, char* pattern, int* returnSize)
{
int m=wordsSize;
int n=strlen(pattern);
char** res=(char**)malloc(sizeof(char*)*m);
for(int i=0;i<m;i++)
{
res[i]=(char*)malloc(sizeof(char)*(n+1));
}
int b[26]={0};
int c[26]={0};
int diff[26]={0};
int count=0;
int count2;
int flag;
for(int i=0;i<m;i++)
{
flag=1;
count2=0;
for(int j=0;j<n;j++)
{
if(b[words[i][j]-'a']==0)
{
b[words[i][j]-'a']=1;
if(c[pattern[j]-'a']==0)
{
c[pattern[j]-'a']=1;
diff[words[i][j]-'a']=words[i][j]-pattern[j];
}
else
{
flag=0;
break;
}
}
else if(c[pattern[j]-'a']==0 || diff[words[i][j]-'a']!=words[i][j]-pattern[j])
{
flag=0;
break;
}
}
if(flag)
{
strcpy(res[count],words[i]);
count++;
}
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
}
*returnSize=count;
return res;
}
C++
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern)
{
int m=words.size();
int n=pattern.length();
vector<string> res;
unordered_map<char,char> temp;
set<char> st;
int flag=1;
for(int i=0;i<n;i++)
{
st.insert(pattern[i]);
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(temp.count(words[i][j])<1)
{
temp[words[i][j]]=pattern[j];
//temp.insert(pair<char,char>(words[i][j],pattern[j]));
}
else if(temp[words[i][j]]!=pattern[j])
{
flag=0;
break;
}
}
if(flag && temp.size()==st.size())
{
res.push_back(words[i]);
}
temp.clear();
flag=1;
}
return res;
}
};
python
class Solution:
def findAndReplacePattern(self, words, pattern):
"""
:type words: List[str]
:type pattern: str
:rtype: List[str]
"""
m=len(words)
n=len(pattern)
res=[]
st=set()
for i in range(n):
st.add(pattern[i])
for i in range(m):
flag=1
dic={}
for j in range(n):
if words[i][j] not in dic:
dic[words[i][j]]=pattern[j]
elif dic[words[i][j]]!=pattern[j]:
flag=0
break
if flag and len(dic)==len(st):
res.append(words[i])
return res