主要思路:1.用python字符串的replace方法。
2.对空格split获得list,用‘%20’链接(join)这个list
3.因为替换空格后,字符串长度须要增大。先扫描空格个数,计算字符串应有的长度,从后向前一个个字符复制(须要两个指针)。这样避免了替换空格后,须要移动的操做。
复杂度:O(N)
# -*- coding:utf-8 -*- class Solution: # s 源字符串 def replaceSpace(self, s): # write code here return s.replace(' ', '%20')
# -*- 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'))
# -*- 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'))
注意:逻辑与和比较运算符的优先级python