[Java] clean and fast solution if we can use some native java methods


  • 1
    S

    The idea is straightforward.

    1. split string into array by delimiter " " <== s.split(" ");

    2. put words from array into another list in reverse order

    3. join the list by delimiter " " by calling String.join(delimit, list)

    public String reverseWords(String s) {
        String[] strs = s.split(" ");
        List<String> words = new ArrayList<>();
        for (int i = strs.length - 1; i >= 0; i--) {
            if (!strs[i].isEmpty()) {
                words.add(strs[i]);
            }
        }
        return String.join(" ", words);
    }

  • 0
    P

    great solution! I like the way you use existing methods to your solution


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.