From 51e719a4351fb97ed41ad6995bc6470d5204ad35 Mon Sep 17 00:00:00 2001 From: Eyjan_Huang <81480748+Eyjan-Huang@users.noreply.github.com> Date: Thu, 19 Aug 2021 17:57:39 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AE=80=E5=8C=96=20=E5=89=91=E6=8C=87Offer05.?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC.md=20python=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 减少不必要的变量使用,优化空间复杂度,使用切片替换而不是单个替换 --- problems/剑指Offer05.替换空格.md | 58 +++++++++----------------- 1 file changed, 20 insertions(+), 38 deletions(-) diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 4ae5f9f2..3f373d0d 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -202,45 +202,27 @@ func replaceSpace(s string) string { python: ```python -class Solution(object): - def replaceSpace(self, s): - """ - :type s: str - :rtype: str - """ - list_s = list(s) - - # 记录原本字符串的长度 - original_end = len(s) - - # 将空格改成%20 使得字符串总长增长 2n,n为原本空格数量。 - # 所以记录空格数量就可以得到目标字符串的长度 - n_space = 0 - for ss in s: - if ss == ' ': - n_space += 1 - - list_s += ['0'] * 2 * n_space - - # 设置左右指针位置 - left, right = original_end - 1, len(list_s) - 1 - - # 循环直至左指针越界 - while left >= 0: - if list_s[left] == ' ': - list_s[right] = '0' - list_s[right - 1] = '2' - list_s[right - 2] = '%' - right -= 3 - else: - list_s[right] = list_s[left] - right -= 1 - - left -= 1 +class Solution: + def replaceSpace(self, s: str) -> str: + counter = s.count(' ') - # 将list变回str,输出 - s = ''.join(list_s) - return s + res = list(s) + # 每碰到一个空格就多拓展两个格子,1 + 2 = 3个位置存’%20‘ + res.extend([' '] * counter * 2) + + # 原始字符串的末尾,拓展后的末尾 + left, right = len(s) - 1, len(res) - 1 + + while left >= 0: + if res[left] != ' ': + res[right] = res[left] + right -= 1 + else: + # [right - 2, right), 左闭右开 + res[right - 2: right + 1] = '%20' + right -= 3 + left -= 1 + return ''.join(res) ```