From c79cc4845411209b7ce143ebc4f98adfd969b2b2 Mon Sep 17 00:00:00 2001 From: yff-1996 Date: Tue, 15 Jun 2021 16:19:01 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A00151.=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D?= =?UTF-8?q?=20Python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0151.翻转字符串里的单词.md | 51 ++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index d76734e4..a174d550 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -318,6 +318,57 @@ class Solution { Python: +```Python3 +class Solution: + #1.去除多余的空格 + def trim_spaces(self,s): + n=len(s) + left=0 + right=n-1 + + while left<=right and s[left]==' ': #去除开头的空格 + left+=1 + while left<=right and s[right]==' ': #去除结尾的空格 + right=right-1 + tmp=[] + while left<=right: #去除单词中间多余的空格 + if s[left]!=' ': + tmp.append(s[left]) + elif tmp[-1]!=' ': #当前位置是空格,但是相邻的上一个位置不是空格,则该空格是合理的 + tmp.append(s[left]) + left+=1 + return tmp +#2.翻转字符数组 + def reverse_string(self,nums,left,right): + while left Date: Tue, 15 Jun 2021 18:42:59 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0151.=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D?= =?UTF-8?q?=20python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0151.翻转字符串里的单词.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index a174d550..c76ff0e1 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -359,10 +359,10 @@ class Solution: return None #4.翻转字符串里的单词 - def reverseWords(self, s): #测试用例:"the sky is blue - l = self.trim_spaces(s) #输出:"the sky is blue" - self.reverse_string( l, 0, len(l) - 1) #输出:"blue is sky the" - self.reverse_each_word(l) #输出:"blue is sky the" + def reverseWords(self, s): #测试用例:"the sky is blue" + l = self.trim_spaces(s) #输出:['t', 'h', 'e', ' ', 's', 'k', 'y', ' ', 'i', 's', ' ', 'b', 'l', 'u', 'e' + self.reverse_string( l, 0, len(l) - 1) #输出:['e', 'u', 'l', 'b', ' ', 's', 'i', ' ', 'y', 'k', 's', ' ', 'e', 'h', 't'] + self.reverse_each_word(l) #输出:['b', 'l', 'u', 'e', ' ', 'i', 's', ' ', 's', 'k', 'y', ' ', 't', 'h', 'e'] return ''.join(l) #输出:blue is sky the