leetcode Reverse words in a string Python
刚接触python不久,被python的简洁强大迷倒了,在做leetcode,Reverse words in a string时,刚开始还是传统的思路想着怎么处理空格问题一直测试不通过,写的很罗嗦被师弟吐槽说你写的代码好丑,好心塞。
废话不多说直接奉上思路代码:
翻转字符串如:"Hello I am echo",输出"echo am I Hello"
可以翻转两次字符串即首先变为" ohce ma I olleH",在对每个字符串翻转即为"echo am I Hello";当然也可以先翻转单个字符串,在对整体字符串翻转,一样的效果。此题中掌握python处理两个函数即翻转和取字符串,其中split()的作用是从一个字符串中取出单个字符串存储到一个list中。
如:s=" hello echo ", s.split()=['hello','echo']
1 class Solution: 2 # @param s, a string 3 # @return a string 4 def reverseWords(self, s): 5 Length=len(s) 6 if (Length==0): 7 return "" 8 elif(Length==1): 9 if(s[0]==" "): 10 return "" 11 else: 12 return s 13 else: 14 num=s[::-1] 15 list="" 16 flag_start=0 17 tmp="" 18 for i in xrange(Length): 19 if(num[i]==" "): 20 #here we need to know if the space the before the word or after the word 21 #if the check out aword then flag change to true 22 if(flag_start==1): 23 if(len(list)==0): 24 list=list+tmp[::-1] 25 else: 26 list=list+" " 27 list=list+tmp[::-1] 28 start_flag=0 29 tmp="" 30 else: 31 tmp=tmp+num[i] 32 flag_start=1 33 list=list+tmp 34 return list

浙公网安备 33010602011771号