Applied AI Engineer (LLM) coding learning path Level 2 This level · 10 of 31

Reverse Words in a String

Medium Parsing String

Problem

Reverse the order of words in a string. Words are separated by spaces. The returned string should contain a single space between words and no leading or trailing spaces.

Original: LeetCode 151: Reverse Words in a String.

Examples

Example 1

Input`s = "the sky is blue"`
Output`"blue is sky the"`

Example 2

Input`s = " hello world "`
Output`"world hello"`

Example 3

Input`s = "a good example"`
Output`"example good a"`

Constraints

  • 1 <= s.length <= 10^4
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 151: Reverse Words in a Stringleetcode.com
  2. Java SE 17 API: String.splitdocs.oracle.com
Previous
Next