程序员面试金典-面试题01.09-字符串轮转
程序员面试金典这本书很金典,相信上面的题目应该不错。尝试使用c语言解决上面的题目。
本篇为面试题01.09-字符串轮转,leetcode链接如下:leetcode
题目为判断一个字符串是否为另一个字符串的旋转。
字符串轮转。给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成(比如,waterbottle是erbottlewat旋转后的字符串)。
示例1:
输入:s1 = "waterbottle", s2 = "erbottlewat"
输出:True
示例2:
输入:s1 = "aa", s2 = "aba"
输出:False
提示:
字符串长度在[0, 100000]范围内。
说明:
你能只调用一次检查子串的方法吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-rotation-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我用暴力解法(循环遍历)来进行解决。
int my_strlen(char * s1) //计算字符串长度
{
int ret = 0;
if(s1 == NULL)
return 0;
while((*s1)!='\0')
{
ret++;
s1++;
}
return ret;
}
bool isFlipedString(char* s1, char* s2){
if((s1==NULL) && (s2==NULL))
return true;
if(s1 == NULL || s2 == NULL)
return false;
int len_s1 = my_strlen(s1);
int len_s2 = my_strlen(s2);
if(len_s1 != len_s2)
return false; //长度不同,自然不是旋转的字符串
//printf("%d\n",len_s1);
int n = len_s1;
if(n==0)
return true;
int is_fliped = 1;
for(int i=0;i<n;i++)
{
int t = i;
is_fliped = 1;
for(int j=0;j<n;j++)
{
if(s1[(t+n)%n]!=s2[j])
{
is_fliped = 0;
break;
}
else{
t++;
}
//printf("equal\n");
}
if(is_fliped==1)
{
break;
}
}
if(is_fliped==1)
return true;
return false;
}