標籤:cte ati end could question 想法 數組 example art
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?
1、剛開始的想法是找到第一個和最後一個單詞,然後交換他們兩個,但是遇到的問題是兩個單詞長度不一致的時候會很麻煩,就需要將剩餘的字串整個進行移動,麻煩,且效率很低。
2、參考了discuss,發現很其實想法很簡單,就是分兩步:第一步就是把整個字串倒過來,第二步就是再翻回來之後再把每個單詞反轉一次就好了。
public class Solution { public void reverseWords(char[] s) { int len = s.length; reverse(s, 0, len - 1); int start = 0; for (int i = 0; i < len - 1; i++){ if (s[i] == ‘ ‘){ reverse(s, start, i - 1); start = i + 1; } } reverse(s, start, len - 1); } private void reverse(char[] s, int start, int end){ while (start < end){ char ch = s[start]; s[start] = s[end]; s[end] = ch; start++; end--; } }}
leetcode 186. Reverse Words in a String II 旋轉字元數組 ---------- java