Skip to content

Latest commit

 

History

History
110 lines (93 loc) · 2.9 KB

2022-02-01-105520-557_reverse_words_in_a_string_iii.org

File metadata and controls

110 lines (93 loc) · 2.9 KB

557. Reverse Words in a String III

Description

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Constraints:

  1. $1\leq s.length \leq 5*104$
  2. s contains printable ascii characters
  3. s does not contain any leading or trailing spaces
  4. There is at least one word in s
  5. All the words in s are separated by a single space

Examples:

Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Input: s = "God Ding"
Output: "doG gniD"

Solution

Understanding the problem

Not too much to write here.

Algorithm

With Python we can simply split the string by space, do reverse and then join then back together with a space.

Code

def reverseWords(s):
    """
    :type s: str
    :rtype: str
    """
    return " ".join([w[::-1] for w in s.split(" ")])

# tests
s = "t"
target = "t"
print(reverseWords(s) == target)

s = "Let's take LeetCode contest"
target = "s'teL ekat edoCteeL tsetnoc"
print(reverseWords(s) == target)

Complexity

Time complexity:

O(N), N is length of s.

Space complexity:

O(N), N is length of s, as we need to store the temporary reversed list of words.

Leetcode solution

nil.

<<imports for typing>>

Time complexity:

Space complexity:

More analysis

General thoughts

What if there is leading/trailing spaces? What if there are consecutive spaces?

I think in an interview I’d just go with regex to reduce these two questions in the the original question and solve it.

Related problems

Log time