Reverse words in string

Problem Statment

Leetcode #151

Given an input string s, reverse the order of the words.

word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Example 1

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

Example 2

Input: s = "  hello world  "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3

Input: s = "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Constraints

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

Golang Solution

func reverseWords(s string) string {
	s = strings.TrimLeft(s, " ")
	s = strings.TrimRight(s, " ")

	// split using white spaces
	stArr := strings.Split(s, " ")
	var result []byte

  // traverse in reverse direction
	for i := len(stArr) - 1; i >= 0; i-- {
		result = append(result, []byte(stArr[i])...)
		
		// skip appending space for last word
		if i > 0 {
			result = append(result, ' ')
		}
	}

	return string(result)
}

Optimised Version

func reverseWords(s string) string {
    // Split the string by spaces (automatically trims leading/trailing spaces and handles multiple spaces)
    words := strings.Fields(s)

    // Reverse the order of words
    for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
        words[i], words[j] = words[j], words[i]
    }

    // Join the reversed words with a single space
    return strings.Join(words, " ")
}

Visit https: https://codeandalgo.com for more such contents

Also Check

Leave a Reply

Your email address will not be published. Required fields are marked *