Recommended Posts

How To Reverse Words in a String (Python, Typescript and Go)

0 comments

simplestack0.312 months agoPeakD5 min read


https://files.peakd.com/file/peakd-hive/simplestack/23wWRKMjQViNco8v1XCYR24Xr3BRriyY6p3mrYuUT6MmcfryQypv2KyEYcMZxmkaCLo9L.png

Write a function that takes a string as input and returns a new string with the words in reverse order. Words are sequences of non-space characters and are separated by one or more spaces in the input string.

The output string should have only single spaces between the reversed words, and no leading or trailing 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.

Solution in Python

class Solution:
    def reverseWords(self, s: str) -> str:
        """
        Reverses the order of words in a given string.

        Args:
            s: The input string containing words separated by spaces.

        Returns:
            A string with the words in reverse order, separated by single spaces,
            with no leading or trailing spaces.
        """

        # Split the input string into a list of words, using spaces as delimiters.
        # split() handles multiple spaces and removes leading/trailing spaces by default.
        split_words_list = s.split()

        # Initialize an empty list to store the reversed words.
        reversed_words_list = []

        # Iterate through the list of words in reverse order.
        # reversed() returns an iterator that yields items in reverse.
        for item in reversed(split_words_list):
            # Append each word to the reversed list.
            reversed_words_list.append(item)

        # Join the reversed list of words into a single string, using a single space
        # as the separator. This creates the final reversed string.
        reversed_str = " ".join(reversed_words_list)

        # Return the string containing the reversed words.
        return reversed_str

Solution in Typescript

function reverseWords(s: string): string {
    // Split the input string into an array of words, using spaces as delimiters.
    // split() handles multiple spaces and removes leading/trailing spaces by default.
    const splitWordsList: string[] = s.trim().split(" ");
    const compactSplitWordsList: string[] = splitWordsList.filter(item => item !== "");

    // Reverse the order of words in the array.
    const reversedWordsList: string[] = compactSplitWordsList.reverse();

    // Join the reversed array of words into a single string, using a single space
    // as the separator. This creates the final reversed string.
    const reversedStr: string = reversedWordsList.join(" ");

    // Return the string containing the reversed words.
    return reversedStr;
}

Solution in Go

import (
        "strings"
)

func reverseWords(s string) string {
        // Trim leading and trailing spaces from the input string.
        trimmedString := strings.TrimSpace(s)

        // Split the trimmed string into a slice of words, using spaces as delimiters.
        // strings.Fields handles multiple spaces and removes leading/trailing spaces.
        splitWordsList := strings.Fields(trimmedString)


    // Go's strings.Fields already handles removal of empty strings, so the below filter is unnecessary.
    // However, including for demonstration of filter-like logic in Go.

        compactSplitWordsList := make([]string, 0, len(splitWordsList)) // Pre-allocate for efficiency
        for _, item := range splitWordsList {
                if item != "" {
                        compactSplitWordsList = append(compactSplitWordsList, item)
                }
        }


        // Reverse the order of words in the slice.
        // Go doesn't have a built-in reverse function for slices, so we have to implement it.
        for i, j := 0, len(compactSplitWordsList)-1; i < j; i, j = i+1, j-1 {
                compactSplitWordsList[i], compactSplitWordsList[j] = compactSplitWordsList[j], compactSplitWordsList[i]
        }

        // Join the reversed slice of words into a single string, using a single space
        // as the separator. This creates the final reversed string.
        reversedStr := strings.Join(compactSplitWordsList, " ")

        // Return the string containing the reversed words.
        return reversedStr
}

The code’s purpose is to reverse the order of words in a given string. It does this in the following general steps:

  1. Splitting: The input string is broken down into individual words, using spaces as the separators. Multiple spaces are treated as a single separator, and any extra spaces at the beginning or end of the string are ignored. This results in a list of words.
  2. Filtering (Optional but good practice): Any empty “words” that might have resulted from multiple consecutive spaces in the original string are removed. This ensures that only actual words are processed.
  3. Reversing: The order of the words in the list is reversed. The first word becomes the last, the second becomes the second to last, and so on.
  4. Joining: The reversed list of words is combined back into a single string. The words are joined together with single spaces between them.
  5. Returning: The newly constructed string, containing the reversed words, is returned as the result.

If you liked this content I’d appreciate an upvote or a comment. That helps me improve the quality of my posts as well as getting to know more about you, my dear reader.

Muchas gracias!

Follow me for more content like this.

X | PeakD | Rumble | YouTube | Linked In | GitHub | PayPal.me | Medium

Down below you can find other ways to tip my work.

BankTransfer: "710969000019398639", // CLABE
BAT: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
ETH: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
BTC: "33xxUWU5kjcPk1Kr9ucn9tQXd2DbQ1b9tE",
ADA: "addr1q9l3y73e82hhwfr49eu0fkjw34w9s406wnln7rk9m4ky5fag8akgnwf3y4r2uzqf00rw0pvsucql0pqkzag5n450facq8vwr5e",
DOT: "1rRDzfMLPi88RixTeVc2beA5h2Q3z1K1Uk3kqqyej7nWPNf",
DOGE: "DRph8GEwGccvBWCe4wEQsWsTvQvsEH4QKH",
DAI: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875"

Comments

Sort byBest