旋转表示通过将另一个字符串向右或向右移动一个字符串来创建一个字符串。例如abc和cab是旋转的,abcd和bacd不是旋转的。 我写了下面的代码,但它没有通过最后一个测试用例(不知道它是什么)。谁能给我关于一些提示哪里出错或有任何更有效的算法:比较两个字符串以查看它们是否为旋转
int isLetterInWord(char c, char* word)//find first letter in the word which is equal to c
{
int len = strlen(word);
for(int i=0; i<len; ++i)
{
if(c==word[i])
return i;
}
return -1;
}
int isRotation(char* word1, char* word2)
//check if word1 and word2 are rotation. if so return 1 otherwise -1
{
if(word1 == NULL && word2 == NULL)
return 1;
int len1 = strlen(word1);
int len2 = strlen(word2);
if(len1!= len2)
return -1;
for(int i=0; i<len1; ++i)
{
int pos = isLetterInWord(word1[i], word2);
if(pos == -1)
return -1;
else
{
int p1 = i, p2 = pos;
int cnt=0;
while(cnt<len1)
{
if(word1[p1++]!=word2[p2++])
break;
if(p1==len1)p1=0;
if(p2==len2)p2=0;
cnt++
}
if(cnt==len1)
return 1;
}
}
return -1;
}
提示:看看tes没有看到它是什么的情况。 – 2014-11-03 06:27:45
您不知道代码失败的测试用例,所以我认为它是用于编码竞争。错误可能在于阅读字符串进行比较,也许你遇到了一个尺寸限制或忘记了迎合空间。长字符串也有可能超时;您的解决方案不是最高效的。 – 2014-11-03 07:10:32