题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:
字符数组插入,就是考虑插入位后面的移动。考虑从后往前插入,才能移动最少的位数。
遍历一遍记录需要插入的次数,根据剩余插入次数来移动元素。
class Solution
{
public:
void replaceSpace(
char *str,
int length)
{
int spaceNUms =
0;
for (
int i =
0; i < length; i++
)
{
if (str[i] ==
' ')
{
++
spaceNUms;
}
}
for (
int j = length -
1; j >=
0; j--
)
{
if (str[j] !=
' ')
str[j +
2 * spaceNUms] =
str[j];
else
{
--
spaceNUms;
str[j +
2 * spaceNUms] =
'%';
str[j +
2 * spaceNUms +
1] =
'2';
str[j +
2 * spaceNUms +
2] =
'0';
}
}
}
};
转载于:https://www.cnblogs.com/ruoh3kou/p/10042325.html
相关资源:数据结构—成绩单生成器