DevPath

← All problems

Reverse Words in a String

Medium strings

Description

Reverse the order of the words in a string, collapsing runs of whitespace into single spaces and trimming the ends.

Constraints

0 <= length <= 100000

Examples

Input: s = "the sky is blue"

Output: "blue is sky the"

Hints (1)
  • Split on whitespace, drop empties, reverse and join with a single space.

Solutions

Split, reverse, join. (requires "strings") · Time O(n) · Space O(n)

func reverseWords(s string) string {
    fields := strings.Fields(s)
    for i, j := 0, len(fields)-1; i < j; i, j = i+1, j-1 {
        fields[i], fields[j] = fields[j], fields[i]
    }
    return strings.Join(fields, " ")
}

Create a free account to submit solutions, track progress and save problems.

Create account