問題:
請實現(xiàn)一個函數(shù),將一個字符串中的空格替換成“%20”瞬逊。例如哎媚,當(dāng)字符串為We Are Happy.則經(jīng)過替換之后的字符串為We%20Are%20Happy垫言。
思路:
- 找到空格的個數(shù)
- 創(chuàng)建一個新的字符串個數(shù)為空格*2+原字符串長度
- 進(jìn)行復(fù)制杉女,在空格處用%20取代
代碼實現(xiàn)
// 第一種思路 從后往前填充字符串?dāng)?shù)組瞻讽,效率較高
class Solution {
public:
void replaceSpace(char *str,int length) {
int count = 0;
for (int i = 0; i < length; ++i) {
if (str[i] == ' ') {
++count;
}
}
count *= 2;
int lastSeek = length+count;
for (int i = length; i >= 0; --i) {
if (i == lastSeek) break;
if (str[i] == ' ') {
str[lastSeek--] = '0';
str[lastSeek--] = '2';
str[lastSeek--] = '%';
continue;
}
str[lastSeek--] = str[i];
}
}
};
// 第二種思路鸳吸,從前往后填充字符串?dāng)?shù)組熏挎,效率最低
class Solution {
public:
void replaceSpace(char *str,int length) {
int j = 0;
char dd[100];
for (int i = 0; i < length; ++i,++j)
{
if (str[i] != ' ') {
dd[j] = str[i];
}
else {
dd[j] = '%';
dd[++j] = '2';
dd[++j] = '0';
}
}
strcpy(str,dd);
}
};
// 第三種思路,雙指針?biāo)悸?class Solution {
public:
void replaceSpace(char *str,int length) {
if(str==NULL||length<=0)
return;
int realLength=0;
int blank=0;
int i=0;
while(str[i]!='\0')
{
++realLength;
if(str[i]==' ')
++blank;
++i;
}
int newLength=realLength+blank*2;
if(newLength>length)
return;
int index=realLength;
int newIndex=newLength;
while(index>=0&&newIndex>index)
{
if(str[index]==' ')
{
str[newIndex--]='0';
str[newIndex--]='2';
str[newIndex--]='%';
}
else
str[newIndex--]=str[index];
--index;
}
}
};