LeetCode 75

Reverse Words in a String

Problem
LC 151
Topic
Array / String
File
official75_LC151ReverseWordsInAString.java
Path
pkg5leetcode/official75/official75_LC151ReverseWordsInAString.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC151ReverseWordsInAString.java
Approach
Split on spaces, reverse order, join.
Complexity
Time O(n), Space O(n)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC151ReverseWordsInAString.java
1package pkg5leetcode.official75;2 3/*4 * Reverse Words in a String | LC 1515 * APPROACH: Split on spaces, reverse order, join.6 * COMPLEXITY: Time O(n), Space O(n)7 */8public class official75_LC151ReverseWordsInAString {9    static String reverseWords(String s) {10        String[] parts = s.trim().split("\\s+");11        StringBuilder sb = new StringBuilder();12        for (int i = parts.length - 1; i >= 0; i--) {13            if (sb.length() > 0) sb.append(' ');14            sb.append(parts[i]);15        }16        return sb.toString();17    }18 19    public static void main(String[] args) {20        check("blue is sky the".equals(reverseWords("the sky is blue")), "case1");21        check("world hello".equals(reverseWords("  hello world  ")), "case2");22        System.out.println("all tests passed");23    }24 25    static void check(boolean cond, String name) {26        if (!cond) throw new AssertionError("FAILED: " + name);27        System.out.println("  PASS " + name);28    }29}