天天看點

将一個字元串後面的幾個字元移到前面

如:原題要求将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
 * [email protected]    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個字元在第二次遞歸的時候将後面兩個移到了前面,一時無語,想了半天也沒太好的辦法。

繼續閱讀