题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
代码
//变量命名真是辣鸡 orz
class Solution
{
public:
void replaceSpace(char *str, int length)
{
//i 原始字符串长, j 替换后字符串长
int i, j, count=0;
if(NULL == str || length <= 0)
{
return;
}
for(i = 0; str[i] != '\0'; i++)
{
if(str[i] == ' ')
{
count++;
}
}
j = i + count * 2;
if(j > length)
{
return ;
}
while(j > i && i >= 0)
{
if(str[i]==' ')
{
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
i--;
}
else
{
str[j--] = str[i--];
}
}
}
};
运行结果
运行时间:6ms
占用内存:604k
解题思路
遍历
时间复杂度 O(n),空间复杂度 O(1)