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?
这道题要求in-place做法,不能使用extra space, 那么,做法跟Rotate Array那道题非常相似
(1)reverse the whole array
(2)reverse each subarray seperated by ' '
1 public class Solution { 2 public void reverseWords(char[] s) { 3 if (s.length == 0) return; 4 reverse(s, 0, s.length-1); 5 int last = 0; 6 for (int i=0; i<s.length; i++) { 7 if (s[i] == ' ') { 8 reverse(s, last, i-1); 9 last = i + 1;10 }11 }12 }13 14 public void reverse(char[] s, int l, int r) {15 while (l <= r) {16 int temp = s[l];17 s[l] = s[r];18 s[r] = temp;19 l++;20 r--;21 }22 }23 }
新闻热点
疑难解答