[Leetcode] (python): 151-reverse Words in a String

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.