forked from nidhisha-shetty/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse-words-in-a-string.py
40 lines (38 loc) · 1.11 KB
/
reverse-words-in-a-string.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
'''
P.S: Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words.
The returned string should only have a single space separating the words. Do not include any extra spaces.
'''
#Solution:
import re
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s = re.sub(' +', ' ', s)
new_s = ''
li = s.split(' ')
li=li[::-1]
for x in li:
new_s+=x
new_s+=' '
return new_s.strip()
#Solution2:
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s = " ".join(s.split())
new_s = ''
li = s.split(' ')
li=li[::-1]
for x in li:
new_s+=x
new_s+=' '
return new_s.strip()