面試5題:
題目:請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串為We Are Happy.則經過替換之后的字符串為We%20Are%20Happy。
方法一:
# -*- coding:utf-8 -*- class Solution: # s 源字符串 def replaceSpace(self, s): # write code here return '%20'.join(s.split(' '))
方法二:
# -*- coding:utf-8 -*- class Solution: # s 源字符串 def replaceSpace(self, s): # write code here return s.replace(' ','%20')
方法三:
劍指offer解法:①先計算源字符串數組長度,並統計空格數量②新字符串數組長度=源數組長度+2*空格數量③在新字符串數組上,從后向前遍歷,通過兩個index移動並復制。
# -*- coding:utf-8 -*- class Solution: # s 源字符串 def replaceSpace(self, s): # method 1: #return '%20'.join(s.split(' ')) # method 2: #return s.replace(' ','%20') # method 3: #計算空格數量 s=list(s) count=0 for e in s: if e == ' ': count+=1 p1=len(s)-1 # p1為原始字符串數組末尾的index #求新數組長度 s+=[None]*(count*2) p2=len(s)-1 # p2為新字符串數組末尾的index while p1>=0: if s[p1]==' ': for i in ['0','2','%']: s[p2]=i p2-=1 else: s[p2]=s[p1] p2-=1 p1-=1 return ''.join(s)
