LeetCode 筆試題 字符串空格替換

問題描述

 

將 “we are happy”中的空格替換爲“%20”。

即輸入“we are happy”

輸出“we%20are%20happy”

 

 

代碼一

//如果直接遍歷碰到空格,後面所有的往後移動,則徒勞的移動太多,
//目標:所有的字符串一次移動到位,移動最少
//1.統計空格的數量
//2.確定直接就在原來的字符串上移動,節省空間
//3.確定從前往後遍歷(需要新開字符串),還是從後往前遍歷(不用新開,從後往前沒一個字符串都是一次移動到位)
void Replace(char *str, int len)
{
	assert(str != NULL);
	int count = 0;
	char *p = str;
	int lenChar = 0;
	//統計空格數目
	while (*p != '\0')
	{
		if (*p == ' ')
		{
			count++;
		}
		lenChar++;
		p++;
	}
	int newlen = count * 2 + lenChar;
	if (newlen > len)
	{
		return;
	}
	int i = lenChar;
	int j = newlen;
	while (i >= 0 && j >=0)
	{
		if (str[i] == ' ')
		{
			str[j--] = '0';
			str[j--] = '2';
			str[j--] = '%';
		}
		else
		{
			str[j--] = str[i];
		}
		i--;
	}

}
int main()
{
	char str[100] = " a  sl  awql   dwle   awq   ";
	Replace(str, 100);
	printf("%s\n", str);
	getchar();
	return 0;
}

代碼二:利用近容器string及其相關函數 

 

void Replace(string &str)
{
	/*
	遍歷str
	若爲空格 erase空格  分別insert % 2 0;
	注意!!!  迭代器失效問題 每次 erase或insert都要用it保存返回值
	由於是在當前位置插入 因此要 0  2 % 這樣插入  然後it要向後偏移3個,跳過%20 進行遍歷
	*/
	auto it = str.begin();
	while (it != str.end())
	{
		if (*it == ' ')
		{
			it = str.erase(it);
			it = str.insert(it, '0');
			it = str.insert(it, '2');
			it = str.insert(it, '%');
			it += 3;
		}
		else
		{
			++it;
		}
	}
}
int main()
{
	string str = "we are happy";
	Replace(str);
	for (char val : str)
	{
		cout << val;
	}
	cout << endl;
	getchar();
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章