557.反转字符串中的单词

一、暴力

看到第一想法,首先就是找到一个空格,将空前的那个单词反转。利用了一个for循环,对于每个单词还有一个while循环。速度感人。

执行用时: 440 ms在Reverse Words in a String III的Python3提交中击败了0.84% 的用户
内存消耗: 14.2 MB在Reverse Words in a String III的Python3提交中击败了0.62% 的用户
class Solution:
    def reverseWords(self, s):
        x = 0
        num = []
        for i in s:
            num.append(i)
        for i in range(len(s)):
            if  i == len(s)-1:
                while x < i:
                    num[x],num[i] = num[i],num[x]
                    x += 1
                    i -= 1
            if  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% 的用户
class Solution:
    def reverseWords(self, s):
        x = 0
        num = []
        for i in s:
            num.append(i)
        i = 0
        while i < len(s):
            if  i == len(s)-1:
                while x < i:
                    num[x],num[i] = num[i],num[x]
                    x += 1
                    i -= 1
                break
            if  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+1
            else:
                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% 的用户
class Solution:
    def reverseWords(self, s):
        num = []
        k = 0
        for i in s:
            num.append(i)
        i = 0
        while i < len(num):
            if  i == len(s)-1:
                if k == 0:
                    num[::]=num[::-1]
                else:
                    num[k::] = num[i:k-1:-1]
                break
            if  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     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值