題目1510:替換空格
題目:http://ac.jobdu.com/problem.php?pid=1510
- 題目描述:
-
請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
- 輸入:
-
每個輸入文件僅包含一組測試樣例。
對於每組測試案例,輸入一行代表要處理的字符串。
- 輸出:
-
對應每個測試案例,出經過處理後的字符串。
- 樣例輸入:
-
We Are Happy
- 樣例輸出:
-
We%20Are%20Happy
這個題和LeetCode上的一個題一樣。關鍵在於向字符串數組插入時,需要移動後序元素的問題。如果從前往後插入,則每次後序元素都需要移動,開銷O(N^2),這種問題顯然應該逆向插入,算好需要移動的位置,一次移動到位。爲了計算正確的位置,顯然需要先遍歷一遍數組,查看有多少空格。
#include<iostream>
#include<string>
using namespace std;
void replace(string &str)
{
int i,j,count=0;
int n=str.size();
for(i=0;i<n;i++){
if(str[i]==' ')count++;
}
//擴展str的長度
str=str+string(count*2,' ');
//逆向遍歷
j=n-1;
for(i=n-1;i>=0;i--)
{
if(str[i]==' '){
//移動
for(j;j>i;j--)
str[j+count*2]=str[j];
str[j]='%';
str[j+1]='2';
str[j+2]='0';
j--;
count--;
}
if(count==0)break;
}
}
int main()
{
string str;
getline(cin,str);
replace(str);
cout<<str<<endl;
}