请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
1 # -*- coding:utf-8 -*- 2 class Solution: 3 # s 源字符串 4 def replaceSpace(self, s): 5 n = len(s) 6 whitespace = 0 7 for ss in s: 8 if ss ==' ': 9 whitespace += 1 10 ary = [' '] * (n + whitespace * 2) 11 idx = n + whitespace * 2 - 1 12 for i in range(n-1,-1,-1): 13 if s[i] == ' ': 14 ary[idx] = '0' 15 idx -= 1 16 ary[idx] = '2' 17 idx -= 1 18 ary[idx] = '%' 19 idx -= 1 20 else: 21 ary[idx] = s[i] 22 idx -= 1 23 s = '' 24 s = ''.join(ary) 25 return s 26 # write code here
先计算出扩展后的字符串的长度然后,从后向前遍历,遇到空格,逆序依次插入对应的三个字符。