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 = "
return "
Given s = "
the sky is blue
",return "
blue is sky the
".
三步翻转法, 先把s = the sky is blue ---> eulb si yks eth
然后 挨个单词再翻转一遍.
对于前面的单词碰到空格就翻转 对于最后一个单词当指针走到最后一个字符时候翻转
public class Solution { public void reverseWords(char[] s) { if (s == null || s.length == 0) { return; } rotate(s, 0, s.length - 1); int last = 0; for (int i = 0; i < s.length; i++) { if ( s[i] == ' ') { rotate(s, last, i - 1); last = i + 1; } if (i == s.length - 1) { rotate(s, last, i); } } } public void rotate(char[] s, int left, int right) { if (s == null ||s.length == 0 || left > right) { return; } while (left < right) { char tem = s[left]; s[left] = s[right]; s[right] = tem; left++; right--; } } }
没有评论:
发表评论