557. Reverse Words in a String III

557. Reverse Words in a String III

這一題如果掌握了 151. Reverse Words in a String的核心,只需要修改一小部分的邏輯就可以了。

class Solution:
    def reverseWords(self, s: str) -> str:
        holder = []
        
        slow = 0
        fast = 0
        
        while fast < len(s):
            if s[fast] != " ":
                fast += 1
            else:
                if fast == slow:
                    fast += 1
                    slow += 1
                else:
                    holder.append(s[slow:fast][::-1])
                    fast += 1
                    slow = fast
                    
        if fast != slow:
            holder.append(s[slow:fast][::-1])
        return " ".join(holder)