剑指Offer编程练习002——替换空格
2018-03-23 20:29
337 查看
题目:
请实现一个函数,将一个字符串中的空格替换成“ % 20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We % 20Are % 20Happy。
思路:在原字符串上进行替换,从前向后记录空格数目,从后向前替换
时间复杂度:O(n)
void replaceSpace(char *str, int length) {
int count = 0;
for (int i = 0; i < length; i++)//计算空格数目count
{
if (str[i] == ' ')
count++;
}
for (int i = length - 1; i >= 0; i--)
{
if (str[i] != ' ')
str[i + 2 * count] = str[i];//如果当前的字符不是空格,就将当前的字符向后移2 * count个位置,
else { //如果当前的字符是空格,那么就进行替换,同时把空格数减一
count--;
str[i + 2 * count] = '%';
str[i + 2 * count + 1] = '2';
str[i + 2 * count + 2] = '0';
}
}
}
请实现一个函数,将一个字符串中的空格替换成“ % 20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We % 20Are % 20Happy。
思路:在原字符串上进行替换,从前向后记录空格数目,从后向前替换
时间复杂度:O(n)
void replaceSpace(char *str, int length) {
int count = 0;
for (int i = 0; i < length; i++)//计算空格数目count
{
if (str[i] == ' ')
count++;
}
for (int i = length - 1; i >= 0; i--)
{
if (str[i] != ' ')
str[i + 2 * count] = str[i];//如果当前的字符不是空格,就将当前的字符向后移2 * count个位置,
else { //如果当前的字符是空格,那么就进行替换,同时把空格数减一
count--;
str[i + 2 * count] = '%';
str[i + 2 * count + 1] = '2';
str[i + 2 * count + 2] = '0';
}
}
}
相关文章推荐
- 练习1-21:编写程序entab,将空格串替换为最少数量的制表符和空格。。。(C程序设计语言 第2版)
- 剑指offer编程题——04 替换空格
- 《剑指offer》Python语言 面试题4:替换空格
- 剑指offer(2):替换空格
- 剑指Offer编程练习005——用两个栈实现队列
- 空格替换 剑指offer
- 【剑指Offer】 002 替换空格
- 剑指Offer面试题4:替换字符串中的空格
- 剑指offer(2)—替换空格
- 剑指offer——替换空格的两种方法(Java)
- 剑指offer:替换空格
- (剑指Offer)面试题4:替换空格
- 《剑指offer》面试题05:替换空格
- 第7周 C语言程序设计(新2版) 练习1-21 空格串替换为最小数目的空格和制表符
- 剑指Offer之替换空格
- 《剑指offer》【面试题4:替换空格】
- 《剑指offer》:[9]字符串中替换空格
- 《剑指offer》-将一个字符串中的空格替换成“%20”
- 剑指offer(3):替换空格
- 剑指offer——替换空格 C++