代码改变世界

Leetcode - 186 Reverse Words in a String II

2017-01-14 06:46  Mux1  阅读(147)  评论(0编辑  收藏  举报

题目:

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?

分析:

这题应用的原理是两次求逆等于原String的原则, 第一次将整体String全部求逆, 然后利用单词之间的空格, 再分开求逆,最后实现将整个sentence单词完全倒序的结果. 比较巧妙

代码:

public class Solution {
    public void reverseWords(char[] s) {
      reverse(s, 0, s.length);
      for (int i = 0, j = 0; j <= s.length; j++){
        if (j == s.length || s[j] == ' ') {
          reverse(s, i , j);
          i = j + 1;
        }
      }
    }

    private void reverse(char[] s, int start, int end) {
       for (int i = 0; i < (end - start) / 2; i++) {
          char temp = s[start + i];
          s[start + i] = s[end - i - 1];
          s[end - i - 1] = temp;
       }
    }
}