面试题5:替换空格
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解法1(python)
- 直接使用replace函数
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(' ', '%20')
解法2(python)
- 使用一个列表来转换, 遍历一遍字符串,这个将字符添加至列表中,若遇到‘ ’,则添加%20
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
# return s.replace(' ', '%20')
strLen = len(s)
strList = []
for i in range(strLen):
if s[i] == ' ':
strList.append('%20')
else:
strList.append(s[i])
return ''.join(strList)
解法3(C++)
- 思路: 若是在原字符串上进行的情况,需要从后往前替换, 这样的时间复杂度为O(n); 而从前往后的复杂度为
O
(
n
2
)
O(n^2)
O(n2),不建议使用。
(1)遍历一遍字符串,统计空格数,即可计算出替换后的字符串长度
(2)准备两个指针p1和p2,p1指向原字符串末尾,p2指向替换后的字符串末尾
(3)p1逐渐往前移动,同时将指向的字符复制到p2处,p2也对应的向前移动, 若p1遇到了空格,则p1向前移动一格, p2处插入"%20",同时p2往前移动3格。
(4)若p1和p2指向同一位置, 则完成
class Solution {
public:
void replaceSpace(char *str,int length) {
if (str == nullptr || length <= 0)
return;
int oldLen = 0; // 统计原字符串长度
int blankLen = 0; // 统计空格数
int i = 0;
while(str[i] != '\0')
{
++oldLen;
if(str[i] == ' ')
++blankLen;
++i;
}
int newLen = oldLen + 2*blankLen; // 计算替换后的字符串长度
int indexOld = oldLen;
int indexNew = newLen;
while(indexOld != indexNew)
{
if(str[indexOld] != ' ')
{
str[indexNew] = str[indexOld];
indexNew--;
indexOld--;
}
else
{
str[indexNew--] = '0';
str[indexNew--] = '2';
str[indexNew--] = '%';
indexOld--;
}
}
}
};