classSolution(object):defreverseWords(self,s):""" :type s: str :rtype: str """# s = " ".join(s.split()) # replace interval with only one space. Create a new array! can't use it!s=s+' '# if not add ' ', the last word can not be extractedforiinrange(len(s)):ifs[i]!=" ":# 1.find start which is not " "start=ibreakelse:return""foriinrange(start+1,len(s)):ifs[i]==" ":end=is=s[start:end+1]+s[:start]+s[end+1:]start=i+1# 2.find the next start which is not " "whilestart<len(s)ands[start]==" ":start+=1s=s[:-1]# remove the ' ' at the end of the s, it is with the original first wordreturnsif__name__=='__main__':answer=Solution()printanswer.reverseWords("the sky is blue")
近期评论