天天看點

[LeetCode] Reverse Words in a String III 翻轉字元串中的單詞之三

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

解法一:

<a>class Solution {</a>

下面我們來看不使用字元流處理類,也不使用STL内置的reverse函數的方法,那麼就是用兩個指針,分别指向每個單詞的開頭和結尾位置,确定了單詞的首尾位置後,再用兩個指針對單詞進行首尾交換即可,有點像驗證回文字元串的方法,參見代碼如下:

解法二:

參考資料:

<a href="https://discuss.leetcode.com/topic/85773/nothing-fancy-straight-java-stringbuilder" target="_blank">https://discuss.leetcode.com/topic/85773/nothing-fancy-straight-java-stringbuilder</a>

<a href="https://discuss.leetcode.com/topic/85797/java-two-methods-3-line-using-built-in-and-char-array" target="_blank">https://discuss.leetcode.com/topic/85797/java-two-methods-3-line-using-built-in-and-char-array</a>

,如需轉載請自行聯系原部落客。

繼續閱讀