zoukankan      html  css  js  c++  java
  • 151. Reverse Words in a String

    Given an input string, reverse the string word by word.

    My idea:删除左右两边空格,转换成数组,再把中间空格给改了,再专成字符串,用快慢指针找到单词放进去,很麻烦,所以效果不好。

    class Solution:
        def reverseWords(self, s) :
            a=s.lstrip()
            b=a.rstrip()
            if(b==''):
                return ''
            if(b.count(' ')==0):
                return b
            p=b.index(' ')
            c=list(b)
            while(p<len(c)):
                if(c[p]==' '):
                    while(c[p+1]==' '):
                        del c[p+1]
                p=p+1
            d=''
            for i in range(len(c)):
                d=d+c[i]
            e=d.rindex(' ')
            end=len(d)
            ans=' '
            while(e>=0):
                if(d[e]==' '):
                    ans=ans+d[e:end]
                    end=e
    
                e=e-1
            ans = ans +' '+ d[e+1:end]
            an=ans.lstrip()
            return an
    执行用时 : 92 ms, 在Reverse Words in a String的Python3提交中击败了7.72% 的用户
    内存消耗 : 13.7 MB, 在Reverse Words in a String的Python3提交中击败了5.02% 的用户
     
    别人的就很简单。一句话。。 关键是split的用法学习
    Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
    str.split(str="", num=string.count(str)).
    class Solution(object):
        def reverseWords(self, s):
            """
            :type s: str
            :rtype: str
            """
            return ' '.join(s.strip().split()[::-1])

    这里思路就是先删除左边的空格然后根据空格分隔再倒叙排列出来再rejoin即可 np

  • 相关阅读:
    题解【DP100题1~10】
    新博客已建好!
    题解【语文1(chin1)- 理理思维】
    题解【[BJOI2012]算不出的等式】
    题解【[HAOI2006]受欢迎的牛】
    题解【[FJOI2018]所罗门王的宝藏】
    Redis常用命令
    mysql table 最新更新时间
    中国翻译史阶记
    HTTP Session原理
  • 原文地址:https://www.cnblogs.com/dmndxld/p/10849372.html
Copyright © 2011-2022 走看看