标签:字符 pre join 空格替换 字符串 lse nal 长度 describe
先计算出新字符串的长度,再从后向前替换空格,这样时间复杂度最少,为O(n)。通过列表来操作替换,最后将列表组合成字符串。
class Solution: # s 源字符串 def replaceSpace(self, s): # write code here if not isinstance(s, str) or len(s) <= 0 or s == None: return ‘‘ spaceNum = 0 for i in s: if i == " ": spaceNum += 1 newStrLen = len(s) + spaceNum * 2 newStr = newStrLen * [None] indexOfOriginal, indexOfNew = len(s) - 1, newStrLen - 1 while indexOfNew >= 0 and indexOfOriginal <= indexOfNew: if s[indexOfOriginal] == ‘ ‘: newStr[indexOfNew - 2: indexOfNew + 1] = [‘%‘, ‘2‘, ‘0‘] indexOfNew -= 3 indexOfOriginal -= 1 else: newStr[indexOfNew] = s[indexOfOriginal] indexOfNew -= 1 indexOfOriginal -= 1 return ‘‘.join(newStr)
标签:字符 pre join 空格替换 字符串 lse nal 长度 describe
原文地址:https://www.cnblogs.com/shenhangyu/p/10848245.html