557. Reverse Words in a String III 去掉字串首尾空格方法object.strip()
阿新 • • 發佈:2018-12-30
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()