主要思路: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