From 7bbf3827d1b9aa3a18f4073533ac2934ecc4eab1 Mon Sep 17 00:00:00 2001 From: Lane Zhang Date: Wed, 16 Oct 2024 14:20:41 +0800 Subject: [PATCH] =?UTF-8?q?0151.=E7=BF=BB=E8=BD=AC=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D=20=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0Python=E7=89=88=E6=9C=AC=E5=AE=9E=E7=8E=B05?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0151.翻转字符串里的单词.md | 23 ++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index 9a0cbea4..7c0b7cb1 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -513,6 +513,29 @@ class Solution: return "".join(result) ``` + +(版本五) 遇到空格就说明前面的是一个单词,把它加入到一个数组中。 + +```python +class Solution: + def reverseWords(self, s: str) -> str: + words = [] + word = '' + s += ' ' # 帮助处理最后一个字词 + + for char in s: + if char == ' ': # 遇到空格就说明前面的可能是一个单词 + if word != '': # 确认是单词,把它加入到一个数组中 + words.append(word) + word = '' # 清空当前单词 + continue + + word += char # 收集单词的字母 + + words.reverse() + return ' '.join(words) +``` + ### Go: 版本一: