From 296ef893b4a15d4459e7400bd2bd699b3173bbbc Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Fri, 10 Mar 2023 13:12:53 -0500 Subject: [PATCH] =?UTF-8?q?Update=200151.=E7=BF=BB=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加python解法:使用双指针法移除空格 --- problems/0151.翻转字符串里的单词.md | 42 ++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index dc12ae23..eb78cc9d 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -516,6 +516,48 @@ class Solution: return s[:ps] + s[ps:][::-1] # Must do the last step, because the last word is omit though the pointers are on the correct positions, ``` +```python +class Solution: # 使用双指针法移除空格 + def reverseWords(self, s: str) -> str: + + def removeextraspace(s): + start = 0; end = len(s)-1 + while s[start]==' ': + start+=1 + while s[end]==' ': + end-=1 + news = list(s[start:end+1]) + slow = fast = 0 + while fast0 and news[fast]==news[fast-1]==' ': + fast+=1 + news[slow]=news[fast] + slow+=1; fast+=1 + #return "".join(news[:slow]) + return news[:slow] + + def reversestr(s): + left,right = 0,len(s)-1 + news = list(s) + while left