Saturday, April 11, 2015

151. Reverse Words in a String Leetcode Java

Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Solution:
The basic idea is to determine the position of the white spaces between each word. Use a pointer named tail to track last position of the white space. Make sure the substring is a valid word by check if there are non-space characters between current white space and the tail white space. 
 public String reverseWords(String s) {  
    s=s.trim();  
    StringBuilder sb=new StringBuilder();  
    int tail=s.length();  
    for(int j=s.length()-1;j>=0;j--){  
      if(j<s.length()-1 && s.charAt(j)==' ' && s.charAt(j+1)!=' '){  
        if(tail!=s.length()) sb.append(' ');  
        sb.append(s.substring(j+1,tail));  
        tail=j;  
      }  
      else if(s.charAt(j)==' ') tail=j;  
      else continue;  
    }  
    if(tail!=s.length()) sb.append(' ');  
    sb.append(s.substring(0,tail));  
    return sb.toString();  
   }  

No comments:

Post a Comment