将一个字符串后面的几个字符移到前面

时间:2022-10-17 22:13:11

如:原题要求将ilovebaofeng的后7个字符移到前面得出baofengilove。

要求时间复杂度O(n),空间复杂度O(1)。

初看此题,觉得对位交换一下就可,最多是头上比后面短的情况需要递归,于是也没多想就写了下面代码:

/*************************************************************
* file:move_part_of_string_to_head.c
* brief:switch part of string to the beginning of the string
* yejing@2015.1.19 1.0 creat
*************************************************************/
#include <stdio.h>
#include <string.h>

int m = 7;
#define min(x, y) (x) < (y)? (x) : (y)

void swap(char* x, char* y){
if(!x || !y)
return;
char tmp;
tmp = *x;
*x = *y;
*y = tmp;

return;
}

void switch_string_by_index(int from_index, int to_index, int len, char* pstring){
if(from_index < 0 || to_index < 0 || len <= 0 || !pstring)
return;
while(len){
swap(&pstring[from_index++], &pstring[to_index++]);
--len;
}
return;
}

void recursive_switch_string(char* string, int len, int from_index, int to_index){
printf("len:%d, from_index:%d, to_index:%d \n", len, from_index, to_index);
if(!string || !len)
return;
int exe_len = min(strlen(string) - m, len);

switch_string_by_index(from_index, to_index, exe_len, string);
recursive_switch_string(string, len - exe_len, from_index + exe_len, to_index + exe_len);
return;
}

int main(int argc, char* argv[]){
char pstring[20] = "ilovebaofeng";//这里如果用指针指的话会被当做字符串常量,导致后面无法交换
recursive_switch_string(pstring, m, strlen(pstring) - m, 0);
printf("string after switch is: %s \n", pstring);
}
但是跑起来吓我一跳,居然的出来了这么个玩意儿:baofengoveil。

很明显后面的5个字符在第二次递归的时候将后面两个移到了前面,一时无语,想了半天也没太好的办法。