简繁EN

LeetCodeNo. 015

[LeetCode with Python] 151. Reverse Words in a String

Contents

Problem

Problem page: https://leetcode.com/problems/reverse-words-in-a-string/
Topics: String
Difficulty: Medium
Similar problems: (M) Reverse Words in a String II

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

Analysis

Reverse the order of the words in a sentence. Note that you also need to remove any leading or trailing whitespace and leave just one space between words.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:

# @param s, a string
# @return a string
def reverseWords(self, s):

len_s = len(s)
if len_s < 1:
return s

index_right = len_s - 1
new_s = ""

while index_right >= 0:
while index_right >= 0 and ' ' == s[index_right]:
index_right -= 1
end_index = index_right
while index_right >= 0 and ' ' != s[index_right]:
index_right -= 1
start_index = index_right + 1
word = s[start_index : end_index + 1] if end_index >= 0 else ""
new_s += (word + " ")

return new_s.rstrip()

Article link: https://xnerv.wang/en/leetcode-reverse-words-in-a-string/