186. Reverse Words in a String II

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?

 

可以先把每一个单词reverse,然后整个list reverse。

public void ReverseWords(char[] s) {
       if(s.Length == 0) return ;
       int start = 0;
       int end = 0;
       int i = 0;
       while(end <= s.Length)
       {
           if(end ==s.Length ||  s[end] == ' ')
           {
               ReverseWord(s,start,end-1);
               start =  ++end;
           }
           else end++;
       }
       ReverseWord(s,0,s.Length-1);
    }
    
    public void ReverseWord(char[] s, int start, int end)
    {
         while(start<end)
         {
             char temp = s[start];
             s[start++] = s[end];
             s[end--] = temp;
         }
    }

 

posted @ 2016-09-14 13:22  咖啡中不塌缩的方糖  阅读(107)  评论(0编辑  收藏  举报