Reverse Words in a String

Problem

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

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

Solution

public class Solution {
    public String reverseWords(String s) {
        if (s == null || s.length() == 0) return s;
        String[] tokens = s.split(" +");
        StringBuilder sb = new StringBuilder();
        for (int i = tokens.length - 1; i >= 0; i--) {
            sb.append(tokens[i] + " ");
        }
        return sb.toString().trim();
    }
}

Using built-in reverse method

public class Solution {
    public String reverseWords(String s) {
        if (s == null || s.length() == 0) return s;
        List<String> list = Arrays.asList(s.trim().split(" +")); //Do not forget to trim() here 
        Collections.reverse(list);
        return String.join(" ", list);
    }
}

Analysis

We can either use a StringBuilder and construct it from the reversed order of tokens
Or we can simply convert the tokens to array and then use built-in method Collections.reverse(list)
And then call String.join() to connect tokens together
Notice that we need to use trim() to take care of spaces (if not allowed, use if statement or substring())

results matching ""

    No results matching ""