程序员面试金典-面试题01.09-字符串轮转

程序员面试金典-面试题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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值