algorithm notes: leetcode#557 reverse words in a string iii

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


Analysis

Split string s into different words. For each word, iterate each character backward to generate the reversed word, then combine reversed words and return the string.

Python implementation

1
2
3
4
5
6
7
class :
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join([word[::-1] for word in s.split(' ')])

Java implementation

1
2
3
4
5
6
7
8
9
class {
public String reverseWords(String s) {
String[] words = s.split(" ");
for(int i = 0; i < words.length; i++){
words[i] = new StringBuilder(words[i]).reverse().toString();
}
return String.join(" ", words);
}
}

Time complexity

O(n).

Space complexity

O(n).


557. Reverse Words in a String III
(中文版) 算法笔记: 力扣#557 反转字符串中的单词 III