码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Words in a String III

时间:2017-09-11 00:46:54      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:style   最大   string   使用   range   eve   rds   split()   self   

    这道题属于简单题

  题目:

    技术分享

  思路:

    1、我的思路比较不好,弄出来的代码不够简洁。我采用栈的形式,遍历整个列表,遇到‘ ’或者长度达到了最大(长度这个条件是为了防止示例中没有出现空格,只有一个单词)就把a[]当中的元素全部加到b[]中并添加一个‘ ’,最后去掉b的最后一个元素,再返回‘’。join(b)

    2、大神:只用了一行,他先用spilt将括号去除,再反向排序,再使用‘ ’.join(),最后再反向排序

  代码:

    1、我的垃圾代码:

 1 class Solution(object):
 2     def reverseWords(self, s):
 3         """
 4         :type s: str
 5         :rtype: str
 6         """
 7         a = []
 8         b = []
 9         for i in range(0, len(s) + 1):
10             if i == len(s) or s[i] ==  :
11                 l = len(a)
12                 while l > 0:
13                     b.append(a.pop())
14                     l -= 1
15                 b.append( )
16             else: a.append(s[i])
17         b.pop()
18         
19         return ‘‘.join(b)

    2、大神代码:

  

1 def reverseWords(self, s):
2     return  .join(s.split()[::-1])[::-1]

 

Reverse Words in a String III

标签:style   最大   string   使用   range   eve   rds   split()   self   

原文地址:http://www.cnblogs.com/liuxinzhi/p/7502822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!