Source of the topic:
https://leetcode.com/problems/reverse-words-in-a-string/
Test Instructions Analysis:
Given a string that contains multiple words, flip the word of the string, for example " the sky is blue
", To get "" blue is sky the
.
Topic Ideas:
First get each word, record the word into an array, and flip it over. The case where there are spaces before and after is to be handled.
Code (Python):
classsolution (object):defreversewords (self, s):""": Type S:str:rtype:str""" ifLen (s) = =0:return ""ans=[] Begin= i =0 Mark=True whileI <Len (s):ifS[i]! =' ' andMark:begin=I Mark=FalseifS[i] = =' ' andI > 0 andS[I-1]! =' ': Ans.append (s[begin:i]) whileI < Len (s) andS[i] = =' ': I+ = 1begin=I i+ = 1ifS[-1]! =' ': Ans.append (S[begin:len (s)])#print (ANS)j =len (ans)ifj = =0:return ""Res= Ans[j-1] J-= 1 whileJ >0:res+=' '+ ans[j-1] J-= 1returnRes
View Code
[Leetcode] (python): 151-reverse Words in a String