[Golang][Leetcode][String]刷題系列-151-Reverse Words in a String

151. Reverse Words in a String
Level : Medium
原題連結 : Click
題目 :
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example :
Input: s = “the sky is blue”
Output: “blue is sky the”
Input: s = " hello world "
Output: “world hello”
Input: s = “a good example”
Output: “example good a”
Input: s = " Bob Loves Alice "
Output: “Alice Loves Bob”
Input: s = “Alice does not even like bob”
Output: “bob like even not does Alice”
解題思路 :
- 這題剛好把一些string的操作都包含進去了
- 刪除多餘的空白
- 翻轉字串
- 翻轉單詞
- 刪除多餘的空白可以使用two pointers,首先將一個pointer fast放到一次出現字母出現的位置,再來將另一個pointer slow放在起點的位置,然後開始將fast的值搬到slow,開始同步往後走清除頭部的多餘空白,做一些條件控管,讓連續出現的空白才略過,單一個就繼續複製,可以達到每一個單詞之間留有一個空白的效果 及刪除掉單詞之間多餘的空白,最後再取slice到最後單詞出現的地方,就可以刪除到尾端的空白
- 再來翻轉整個字串
- 最後再執行一些條件控制,讓單詞一個一個翻轉回來就會得到所要的答案
以下是我的解法 - time complexity: O(n) , space complexity: O(1)
Runtime: 0 ms, faster than 100.00% of Go online submissions for Reverse Words in a String.
|
|
最後祝福努力認真的各位 “All your dream of are hidden in your daily life” 我們峰頂見!!!