题目描述:http://ac.jobdu.com/problem.php?pid=1510
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为”We Are Happy.“则经过替换之后的字符串为“We%20Are%20Happy.”
解析:
直观的想法是,新建一个数组,逐个复制,遇到空格时,写入%20,但这需要占用额外空间。
不占用额外空间的算法是原位替换。如果我们顺序的遍历字符串,当遇到空格时,用%20替换空格,这将覆盖掉空格后面的字符 || 如果覆盖前,后移剩余字符串,那么移动的时间复杂度为O(n^2).
因此,采用从后向前复制的方式。
注意:以下的新旧字符串是同一个字符串,只是一个是替换前,一个指替换后
首先统计空格的个数,计算出新字符串的长度,然后用2个指针,1个指向新字符串尾,1个指向旧字符串尾,两指针同步向前,遇到空格时,新索引指针按地址写入%20,当新旧指针相等时说明已经替换完全部空格。
从后向前的处理方式,不会覆盖原有的数据,也不会产生多余的数据移动。
#include <iostream>
using namespace std;
void ReplaceBlank(char str[], int len) {
if (str == NULL || len <= 0)
return;
int blank = 0; //空格数
int oldLen = 0; // 有效字符数
for (int i = 0; i < len && str[i] != '\0'; i++) {
oldLen++;
if (str[i] == ' ')
blank++;
}
int oldIndex = oldLen; //之所以不-1,是因为字符串数组尾部的'\0'
int newIndex = oldLen + 2*blank ;
if (newIndex+1 > len) // 原有数组空间不足
return;
while (newIndex != oldIndex) {
if (str[oldIndex] == ' ') {
str[newIndex--] = '0';
str[newIndex--] = '2';
str[newIndex--] = '%';
} else {
str[newIndex--] = str[oldIndex];
}
oldIndex--;
}
}
int main() {
char str1[30] = "We are happy.";
ReplaceBlank(str1, 30);
cout << str1 << endl;
}