1. 程式人生 > >數據結構——算法之(031)(將字符串中全部小寫字母排在大寫字母的前面)

數據結構——算法之(031)(將字符串中全部小寫字母排在大寫字母的前面)

函數 返回 mod ont content 內容 print har -h

【申明:本文僅限於自我歸納總結和相互交流,有紕漏還望各位指出。 聯系郵箱:[email protected]

題目:

函數將字符串中的字符‘*‘移到串的前部分。前面的非‘*‘字符後移。但不能改變非‘*‘字符的先後順序,函數返回串中字符‘*‘的數量。
題目分析:

1、須要保持非‘*‘字符的順序

2、不開辟額外的空間

3、用快慢指針。指向字符串尾巴,快指針指向非‘*’字符串,慢指針指向‘*‘,然後交換指針內容就可以

算法實現:

#include <stdio.h>
#include <string.h>

int str_move_char_to_head(char *str, char move_char)
{
	int len = strlen(str);
	char *fast = str + len - 1;
	char *slow = fast;
	char temp;

	while(len--)
	{
		if(*slow != move_char)
		{
			slow--;
			fast = slow;
			continue;
		}
		if(*fast == move_char)
		{
			fast--;
			continue;
		}
		
		{
			temp = *fast;
			*fast-- = *slow;
			*slow-- = temp;
		}
	}
}

int main(int argc, char *argv[])
{
	printf("%s----->", argv[1]);
	str_move_char_to_head(argv[1], ‘*‘);
	printf("%s\n", argv[1]);
}


數據結構——算法之(031)(將字符串中全部小寫字母排在大寫字母的前面)