Reverse Words in a String II

Problem:
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?
Analysis:
Similar to rotate array, if a word is detected, reverse the word. Then reverse the whole string. 
Solution:

 class Solution {  
   public void reverseWords(char[] str) {  
     if (str == null || str.length == 0) {  
       return;  
     }  
     int start = 0;  
     for (int end = 0; end < str.length; end++) {  
       if (end == str.length - 1 || str[end+1] == ' ') {  
         reverse(start, end, str);  
         start = end + 2;  
       }  
     }  
     reverse(0, str.length - 1, str);  
   }  
   private void reverse(int start, int end, char[] str) {  
     while (start <= end) {  
       char temp = str[start];  
       str[start] = str[end];  
       str[end] = temp;  
       start++;  
       end--;  
     }  
   }  
 }  

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array