版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mygodhome/article/details/85269146
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
这是最笨的方法。
改了三次。
第一次是空格输出位置不对,且字符串连接重复。
第二次是,逆序单词的出场顺序反了,所以第三次再改就是从头读一遍。这样不好。效率比较低。
前两次的测试用例是:"Let's take LeetCode contest"
第三次是对首部用字符串截取去掉了首部的空格,但是尾部在下面的用例里面出现上面测试用例时没出现的空格。脑子灵光乍现,python可以去掉字符串首尾的空格。这样才终于被accept。
第三次的测试用例是“I love you"
strip是trim掉字符串两边的空格。
lstrip, trim掉左边的空格
rstrip, trim掉右边的空格
class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
a=[]
b=""
c=""
List=s.split(" ")
for word in List:
for c in word:
b=c+b
b=" "+b
listb=b.split(" ")
j=len(listb)-1
for i in range (len(listb)-1):
if j >=1:
c=c+" "+str(listb[j])+ " " +str(listb[j-1])
j-=2
return str(c)[2:].strip()