LeetCode

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".

Java

public class Solution {
    public String reverseWords(String s) {
        if(s.length() < 1) {
            return s;
        }

        String[] words = s.split(" ");
        StringBuilder rst = new StringBuilder();

        for(int i = words.length - 1; i >= 0; i--) {
            if(!words[i].equals("")) {
                rst.append(words[i]).append(" ");
            }
        }
        return rst.length() == 0 ? "" : rst.toString().substring(0, rst.length() - 1);
    }
}