给两个char型数组,之间存在映射关系,判断输入的两个数组是否匹配
映射关系如下:
pattern = "abba" str = "dog cat cat dog" return true
pattern = "abba" str = "dog cat cat fish" return false
pattern = "aaaa" str = "dog cat cat dog" return false
pattern = "abba" str = "dog dog dog dog" return false
表示这个题。。。很无聊
大概分析一下我的思路:
①找一个数组存放str中每个元素的长度,比如说"dog cat cat dog"存放的长度为[3 3 3 3]
②进行两层循环的匹配,外层i范围[0 , strlen(pattern)-1],里层j范围[i+1 , strlen(pattern)-1],如果pattern[i]==pattern[j],判断i和j对应的长度是否一致,不一致返回flase,一致返回true,之后查看每个元素是否一致
③考虑pattern = "abba" str = "dog dog dog dog" 这种情况,判断如果pattern[i]!=pattern[j]时对应的元素是否一致。如果长度不同,那必然不匹配,如果相同,测试是否一致
④在提交时才突然发现一个未考虑的问题,如果pattern = "aaa" str = "cat cat cat cat"这应该也是错的,所以在前期我根据空格的个数是否等于pattern数目-1决定这个方面的对错。
代码如下:
bool wordPattern(char* pattern, char* str) {
if(strlen(pattern) == 0)
return false;
if(strlen(pattern) == 1)
return true;
int length[strlen(pattern)];
int checked[strlen(pattern)];
for(int i=0; i<strlen(pattern); i++)
checked[i] = length[i] = 0;
int blank = 0;
for(int i=0; i<strlen(str); i++)
{
if(str[i]!=' ')
length[blank]++;
else
blank++;
}
if(blank!=strlen(pattern)-1) return false;
int num = 0;
for(int i=0; i<strlen(pattern); i++)
{
for(int j=i+1; j<strlen(pattern); j++)
{
if( (pattern[i]==pattern[j]) && (checked[j]==0) )
{
if(length[i]!=length[j]) return false;
int start_i = 0;
int start_j = 0;
for(int k=0; k<j; k++)
{
if(k<i) start_i += length[k];
start_j += length[k];
}
start_i += i;
start_j += j;
for(int q=0; q<length[i]; q++)
{
if(str[start_i+q] != str[start_j+q])
return false;
}
checked[j]=1;
num++;
}
if( (pattern[i]!=pattern[j]) && (length[i]==length[j]) )
{
int flag = 1;
int start_i = 0;
int start_j = 0;
for(int k=0; k<j; k++)
{
if(k<i) start_i += length[k];
start_j += length[k];
}
start_i += i;
start_j += j;
for(int k=0; k<length[i]; k++)
{
if(str[start_i+k]!=str[start_j+k])
flag = 0;
}
if(flag == 1) return false;
}
}
}
return true;
}