编程之法:字符串反转

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ds1130071727/article/details/88352977

字符串反转 eg:"abcdef"---->"defabc"
解法1:蛮力移位

void LeftShiftOne(char* s, int n)
{
    char t = s[0];
    for (int i = 0; i < n; i++)
    {
        s[i-1] = s[i];
    }
    s[n-1] = t;
}
void LeftRotateString(char* s, int n, int m)
{
    while (m--)
    {
        LeftShiftOne(s, n);
    }
}

解法2:三步反转 (时间复杂度比解1小)
 

void 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)
{
    //若要左移动大于n位,那么与%n是等价的
    m %= n;
    ReverseString(s, 0, m - 1);
    ReverseString(s, m, n - 1);
    ReverseString(s, 0, n - 1);
}

猜你喜欢

转载自blog.csdn.net/ds1130071727/article/details/88352977