码迷,mamicode.com
首页 > 其他好文 > 详细

abcdef->cdefab(字符串旋转)

时间:2014-08-05 14:17:49      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   for   2014   ar   

题目:左旋转字符串
定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部,如把字符串abcdef左旋转2位得到字符串cdefab。请实现字符串左旋转的函数,要求对长度为n的字符串操作的时间复杂度为O(n),空间复杂度为O(n)
思路一、暴力移位法
核心思想:就是把需要移动的字符一步步移动到字符串的尾部

//暴力移位法void leftshiftone(char *s, int n)
{
    char t = s[0];//保存第一个字符
    for(int i = 1;i < n; i++)
        s[i-1] = s[i];
    s[n-1] = t;
}

void leftshift(char *s, int n, int m)
{
    while(m--)
        leftshiftone(s,n);
}

分析时间复杂度和空间复杂度:需要移动m个字符到字符串的尾部,所以需要m*n次操作,时间复杂度为O(mn);同时我们要设立一个变量保存第一个字符,空间复杂度为O(1)

思路二、三步翻转法

反转X^T X=“abc” X^T="cba" (X^TY^T)^T = YX
bubuko.com,布布扣

参考代码:

//三步翻转法.cppvoid ReverseString(char *s, int from, int to)
{
    while(from < to)
    {
        char t = s[from];
        s[from++] = s[to];
        s[to--] = t;
    }
}

void LeftRotateString(char *s, int n, int m)
{
    m %= n;  //如果左移动大于n位,那么和%n是等价的
    ReverseString(s, 0, m-1);//反转[0, m-1] abc->cba
    ReverseString(s, m, n-1);//反转[m, n-1] def->fed
    ReverseString(s, 0, n-1);//反转[0, n-1] cbafed->defabc
}

分析时间复杂度和空间复杂度:时间浮渣度为O(n),空间复杂度为O(1)



abcdef->cdefab(字符串旋转),布布扣,bubuko.com

abcdef->cdefab(字符串旋转)

标签:style   blog   http   color   strong   for   2014   ar   

原文地址:http://blog.csdn.net/to_xidianhph_youth/article/details/38382635

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!