题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
注意事项:
Python字符串是不可以修改的类型,因此在Python中只能创建新的字符串,原来的字符串不能修改。
解题思路1:
用Python字符串的replace方法。
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(' ', '%20')
解题思路2:
对空格split得到list,用‘%20’连接(join)这个list。
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
return '%20'.join(s.split(' '))
if __name__ == '__main__':
a = Solution()
print(a.replaceSpace('r y uu'))
解题思路3:
在C语言中字符串可以替换。
O(n2)的解法
最直观的做法是从头到尾扫描字符串,每一次碰到空格字符的时候做替换。由于是把1个字符替换成3个字符,我们必须要把空格后面所有的字符都后移两个字节,否则就有两个字符被覆盖了。下图展示了从前往后把字符串中的空格替换成'%20'的过程:
假设字符串的长度是n。对每个空格字符,需要移动后面O(n)个字符,因此对含有O(n)个空格字符的字符串而言总的时间复杂度是O(n2)。
O(n)的解法
- Step1. 遍历一次字符串。
这样就能统计出字符串中空格的总数,并可以由此计算出替换之后的字符串的总长度。
以字符串"We are happy."为例,"We are happy."这个字符串的长度是14(包括结尾符号'\0'),里面有两个空格,因此替换之后字符串的长度是18。
- Step2. 从字符串的后面开始复制和替换。
准备两个指针,P1和P2。P1指向原始字符串的末尾,而P2指向替换之后的字符串的末尾。接下来向前移动指针P1,逐个把它指向的字符复制到P2指向的位置,直到碰到第一个空格为止。接着向前复制,直到碰到第二、三或第n个空格。
从上面的分析我们可以看出,所有的字符都只复制(移动)一次,因此这个算法的时间复杂度是O(n),比第一个思路要快。
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
num_space = 0
for i in s:
if i == ' ':
num_space += 1
new_length = len(s) + 2 * num_space
index_origin = len(s) - 1
index_new = new_length - 1
new_string = [None for i in range(new_length)]
while index_origin >= 0 & (index_new > index_origin):
if s[index_origin] == ' ':
new_string[index_new] = '0'
index_new -= 1
new_string[index_new] = '2'
index_new -= 1
new_string[index_new] = '%'
index_new -= 1
else:
new_string[index_new] = s[index_origin]
index_new -= 1
index_origin -= 1
return ''.join(new_string)
if __name__ == '__main__':
a = Solution()
print(a.replaceSpace('r y uu'))
运行时间:24 ms
占用内存:5856K
来源:https://blog.csdn.net/sinat_26811377/article/details/98876388