Left-hand string parsing

The left rotation operation of the string is to transfer several characters in front of the string to the end of the string, please define a function to complete the left rotation operation of the string

Input: abcdef 2
Output: cdefab

Input: abcdef 3
Output: defabc

Suppose that abcdef wants to rotate two left-handed to get cdefad.
Source: Jianzhi offer

The first method you can think of:

暴力求解法:每次左旋一个字符,左旋 k 次达到目标
或者优化一下
1、把 a b 拿出来
2、然后将剩余字符从字符串开头依次放置
3、把 a b 添加到字符串末尾

Although this method can be easily thought of, it is not the optimal solution

The optimization of the left-handed process is as follows:

1. Divide the target string (abcdef) into two parts according to the number of digits to be left-handed.
Insert picture description here
2. Reverse the first half and the second half respectively, and get the following results.
Insert picture description here
3. Reverse the entire string to get the character after the left-handed 2 digits. string
Insert picture description here

According to the above analysis steps, we first need to implement a function to reverse the string

Reverse string function:

void reverse(char* left, char* right) {
    
    
	assert(left && right);

	while (left < right) {
    
    
		char temp = *left;
		*left++ = *right;
		*right-- = temp;
	}
}

Then implement the left-handed string function:

void rotate_left(char* str, int k) {
    
    
	assert(str);
	int len = strlen(str);
	assert(k <= len);//k不能超过数组的长度
	//反转前半部分
	reverse(str, str + k - 1);
	//反转后半部分
	reverse(str + k, str + len - 1);
	//反转整体
	reverse(str, str + len - 1);
}

Guess you like

Origin blog.csdn.net/weixin_46576333/article/details/114934952