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

  • 相关阅读:
    #树#遍历#N叉树的前序遍历
    #树#递归#最大二叉树II
    #树#递归#二叉树的镜像
    #树#递归#最大二叉树
    #树#二叉搜索树的最近公共祖先
    #树#二叉树的直径
    #树#N叉树的后序遍历
    #树#判断平衡二叉树
    webpack+react+nodejs+express前端开发环境搭建
    sublime 玩转react+es6
  • 原文地址:https://www.cnblogs.com/dmndxld/p/10849372.html
Copyright © 2011-2022 走看看