题目:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
题目地址:http://www.nowcoder.com/books/coding-interviews
思路1:从头到尾遍历字符串,遇到空格将空格替换为‘%20’,注意相应移动后面的字符
思路2:首先计算空格个数,获得替换后字符串长度。用两个指针分别指向字符串的尾部,依次往前替换和移动,时间复杂度最小
这个程序本地测试没问题,但是牛客网那个就是通不过,我也是醉了,木有办法了……
void replaceSpace(char *str, int length)
{
int space_cnt = 0;
for (int i = 0; i<length; i++)
{
if (*(str + i) == ' ')
space_cnt++;
}
int newlength = length + space_cnt * 3;
char *new_str = new char[newlength];
int k = 0, j = 0;
while (k<newlength)
{
char c = *(str + j);
if (c != ' ')
{
*(new_str + k) = *(str + j);
k++; j++;
}
else
{
*(new_str + k) = '%';
k++;
*(new_str + k) = '2';
k++;
*(new_str + k) = '0';
k++;
j++;
}
}
for (int x = 0; x < newlength; x++)
{
cout << *(new_str + x);
}
delete new_str;
}
int main()
{
char *str = "hello world";
int num = 11;
replaceSpace(str, num);
return 0;
}