给你一个整数 n
和一个下标从 0 开始的字符串数组 words
,和一个下标从 0 开始的数组 groups
,两个数组长度都是 n
。
两个长度相等字符串的 汉明距离 定义为对应位置字符 不同 的数目。
你需要从下标 [0, 1, ..., n - 1]
中选出一个 最长子序列 ,将这个子序列记作长度为 k
的 [i0, i1, ..., ik - 1]
,它需要满足以下条件:
- 相邻 下标对应的
groups
值 不同。即,对于所有满足0 < j + 1 < k
的j
都有groups[ij] != groups[ij + 1]
。 - 对于所有
0 < j + 1 < k
的下标j
,都满足words[ij]
和words[ij + 1]
的长度 相等 ,且两个字符串之间的 汉明距离 为1
。
请你返回一个字符串数组,它是下标子序列 依次 对应 words
数组中的字符串连接形成的字符串数组。如果有多个答案,返回任意一个。
子序列 指的是从原数组中删掉一些(也可能一个也不删掉)元素,剩余元素不改变相对位置得到的新的数组。
注意:words
中的字符串长度可能 不相等 。
示例 1:
输入:n = 3, words = ["bab","dab","cab"], groups = [1,2,2] 输出:["bab","cab"] 解释:一个可行的子序列是 [0,2] 。 - groups[0] != groups[2] - words[0].length == words[2].length 且它们之间的汉明距离为 1 。 所以一个可行的答案是 [words[0],words[2]] = ["bab","cab"] 。 另一个可行的子序列是 [0,1] 。 - groups[0] != groups[1] - words[0].length = words[1].length 且它们之间的汉明距离为 1 。 所以另一个可行的答案是 [words[0],words[1]] = ["bab","dab"] 。 符合题意的最长子序列的长度为 2 。
示例 2:
输入:n = 4, words = ["a","b","c","d"], groups = [1,2,3,4] 输出:["a","b","c","d"] 解释:我们选择子序列 [0,1,2,3] 。 它同时满足两个条件。 所以答案为 [words[0],words[1],words[2],words[3]] = ["a","b","c","d"] 。 它是所有下标子序列里最长且满足所有条件的。 所以它是唯一的答案。
提示:
1 <= n == words.length == groups.length <= 1000
1 <= words[i].length <= 10
1 <= groups[i] <= n
words
中的字符串 互不相同 。words[i]
只包含小写英文字母。
分析:这道题是 2900 的进阶。做法也类似,只需要把求最长 01 序列的判断条件,增加判断对应位置字符串的汉明距离即可,其它部分不变。
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
bool judge(char *a,char *b)
{
int la=strlen(a),lb=strlen(b);
if(la!=lb)return false;
int t=0;
for(int i=0;i<la;++i)
{
if(a[i]!=b[i])t++;
if(t>1)return false;
}
if(t==1)return true;
return false;
}
char** getWordsInLongestSubsequence(char** words, int wordsSize, int* groups, int groupsSize, int* returnSize) {
int pre[wordsSize+5],dp[wordsSize+5];
for(int i=0;i<=wordsSize;++i)pre[i]=-1,dp[i]=1;
for(int i=0;i<wordsSize;++i)
{
for(int j=i+1;j<wordsSize;++j)
{
if(groups[j]!=groups[i]&&judge(words[i],words[j]))//增加汉明距离点的判断
{
if(dp[j]<dp[i]+1)dp[j]=dp[i]+1,pre[j]=i;
}
}
}
int index=0,temp=0;
for(int i=0;i<wordsSize;++i)
{
if(dp[i]>temp)temp=dp[i],index=i;
}
// printf("temp=%d index=%d\n",temp,index);
char **ans=(char**)malloc(sizeof(char*)*(temp+5));
for(int i=0;i<=temp;++i)
ans[i]=(char*)malloc(sizeof(char)*12);
int t=temp-1;
while(index!=-1)
{
strcpy(ans[t],words[index]);
// printf("t=%d ans=%s word=%s index=%d pre=%d\n",t,ans[t],words[index],index,pre[index]);
index=pre[index];t--;
}
*returnSize=temp;
return ans;
}