From 0fbacd5d9b4c72db15f5f1ddae2c73b320a8c554 Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Sun, 27 Feb 2022 01:19:55 +0800 Subject: [PATCH] modified 151. Add 2 python versions. No need to implement Carlo's idea in such a complecated way by inviting extra space. --- problems/0151.翻转字符串里的单词.md | 32 ++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index ead5fa12..7588cbd6 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -438,6 +438,38 @@ class Solution: ``` +```python +class Solution: + def reverseWords(self, s: str) -> str: + # method 1 - Rude but work & efficient method. + s_list = [i for i in s.split(" ") if len(i) > 0] + return " ".join(s_list[::-1]) + + # method 2 - Carlo's idea + def trim_head_tail_space(ss: str): + p = 0 + while p < len(ss) and ss[p] == " ": + p += 1 + return ss[p:] + + # Trim the head and tail space + s = trim_head_tail_space(s) + s = trim_head_tail_space(s[::-1])[::-1] + + pf, ps, s = 0, 0, s[::-1] # Reverse the string. + while pf < len(s): + if s[pf] == " ": + # Will not excede. Because we have clean the tail space. + if s[pf] == s[pf + 1]: + s = s[:pf] + s[pf + 1:] + continue + else: + s = s[:ps] + s[ps: pf][::-1] + s[pf:] + ps, pf = pf + 1, pf + 2 + else: + pf += 1 + 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, +``` Go: