在Reverse Words in a String III的Python3提交中击败了0.84% 的用户
内存消耗: 14.2 MB
在Reverse Words in a String III的Python3提交中击败了0.62% 的用户
classSolution:defreverseWords(self, s):
x =0
num =[]for i in s:
num.append(i)for i inrange(len(s)):if i ==len(s)-1:while x < i:
num[x],num[i]= num[i],num[x]
x +=1
i -=1if num[i]==' ':
j = i
r = i
while x < j-1:
num[x],num[j-1]= num[j-1],num[x]
x +=1
j -=1
x = r+1
s =''for i in num:
s += i
return s
二、暴力法改进
改成while循环莫名变快了,而且每次提交速度都不一样,真神奇。。。
执行用时: 244 ms
在Reverse Words in a String III的Python3提交中击败了1.35% 的用户
内存消耗: 13.7 MB,
在Reverse Words in a String III的Python3提交中击败了0.62% 的用户
classSolution:defreverseWords(self, s):
x =0
num =[]for i in s:
num.append(i)
i =0while i <len(s):if i ==len(s)-1:while x < i:
num[x],num[i]= num[i],num[x]
x +=1
i -=1breakif num[i]==' ':
j = i
r = i
while x < j-1:
num[x],num[j-1]= num[j-1],num[x]
x +=1
j -=1
x = r+1
i = x+1else:
i +=1
s =''for i in num:
s += i
return s
三、切片
执行用时: 200 ms
在Reverse Words in a String III的Python3提交中击败了2.03% 的用户
内存消耗: 14.1 MB,
在Reverse Words in a String III的Python3提交中击败了0.62% 的用户
classSolution:defreverseWords(self, s):
num =[]
k =0for i in s:
num.append(i)
i =0while i <len(num):if i ==len(s)-1:if k ==0:
num[::]=num[::-1]else:
num[k::]= num[i:k-1:-1]breakif num[i]==' ':if k ==0:
num[:i:]=num[i-1::-1]else:
num[k:i:]=num[i-1:k-1:-1]
k = i+1
i +=1
s =''for i in num:
s += i
return s