【劍指offer】面試題05. 替換空格

解題思路

該題第一眼思路是暴力法,時間複雜度O(n^2),即從前面開始遍歷,碰到空格,則使字符向後移,因此複雜度高;使用雙指針法,從後往前移,使得只需要O(n)時間複雜度即可解決
雙指針法參考自劍指offer,思路見下圖
在這裏插入圖片描述
另外,可以使用string函數,解題速度更快

代碼

/*雙指針法*/
class Solution {
public:
	string replaceSpace(string s) {
		if (s.size()==0)//特判
		{
			return "";
		}
		int len1 = s.size();
		int count = 0;
		for (int i = 0; i < len1; i++)
		{
			if (s[i]==' ')
			{
				count++;
			}
		}
		int p1 = len1-1, p2 = len1 + count * 2-1;//p1指向原始字符串的最後一個字符,p2指向新字符串的最後一個字符
		string temp(count * 2, ' ');
		s += temp;
		while (p1!=p2)//兩者未相遇
		{
			if (s[p1]==' ')//爲空格
			{
				p1--;//p1先移動一位
				for (int i=0;i<3;i++)//p2移動3三位,並增加字符串%20
				{
					if (i==0)
					{
						s[p2--] = '0';
					}
					else if(i==1)
					{
						s[p2--] = '2';
					}
					else 
					{
						s[p2--] = '%';
					}
					
				}
			}
			else {//不爲空格,則後移
				s[p2--] = s[p1--];
			}
		}
		return s;
	}
};


/*利用find,replace函數,寫法簡單,思路清晰*/
class Solution {
public:
	string replaceSpace(string s) {
		string::size_type pos;
		while (true)
		{
			if ((pos=s.find(" "))!=string::npos)//find每次找到出現的第一個空格,如果能找到空格,則將其替換
			s.replace(pos, 1, "%20");
			else break;
			
		}
		return s;
	}
};
發佈了99 篇原創文章 · 獲贊 19 · 訪問量 8175
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章