Easy

Len Chen
1 min readSep 16, 2018

Problem

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

Example 1:

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

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

Solution

Split string into snippets, traverse each snippet and reverse it.

Complexity

It takes O(n) time for splitting and O(n) time for reversing each snippet. Therefore, it needs O(n+n) = O(n) time for entire function.

There is an extra list for saving snippets so space complexity is O(n).

--

--

Len Chen
Len Chen

No responses yet