Reverse Words in a String

Given an input string, reverse the string word by word.
For example,

Given s = "the sky is blue",
return "blue is sky the".

public class Solution {
    //key to the method: use StringBuilder to append strings. 
    public String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return ""; 
        //split to words by space 
        String[] arr = s.split(" ");
        //create a string 
        StringBuilder sb = new StringBuilder();
        //traverse every words in arr 
        for (int i = arr.length - 1; i >= 0; i--) {
            if (!arr[i].equals("")) {
                sb.append(arr[i]).append(" "); 
        return sb.length() == 0 ? "":sb.substring(0, sb.length()-1); 

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s