題目描述
請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串為We Are Happy.則經過替換之后的字符串為We%20Are%20Happy。
主要思路: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'))
注意:邏輯與和比較運算符的優先級