LeetCodeOJ--Reverse Words in a String(python版本)

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

For example,
Given s = "the sky is blue",
return "blue is sky the".

click to show clarification.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
1.测试版本代码:
# -*- coding: cp936 -*-
s = " tian zhai  xing  "
print "Before s:",s
def reverseWords(s):
    L = s.split() #单词拆分成列表
    print "字符串以单词分割成列表: %s" % L
    L.reverse()#反转列表中单词
    print "反转列表中的单词: %s" % L
    s1 = ' '.join(L)#列表以空格分割单词,返回字符串
    print "以空格分隔列表中反转后的单词: %s" % s1
    return s1
    #return s1.rstrip()#字符串删除首尾空格和回车
L = reverseWords(s)
print "Afer L  :",L

2.测试版本截图:

3.提交AC版本代码:
class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        L = s.split()#字符串以单词分隔成列表
        L.reverse()#反转列表中的单词
        s1 = ' '.join(L)#以空格分隔列表中反转后的单词,返回字符串
        return s1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Digital2Slave

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值