https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/
题目描述:给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
思路:
1.按照空格,将字符串分割成单词列表
2.对每个单词进行翻转——用昨天的方法就行
3.再把翻转的单词组合起来。
注意:字符串两端可能会多出来空格,使用strip()方法去除空格。
strip()方法返回删除两端空格后的字符串,但不对原字符串修改。
1 class Solution: 2 def reverseWords(self, s): 3 def reverseString(origin_str): 4 origin_str = list(origin_str) 5 length = len(origin_str) 6 for i in range(length - 1, -1, -1): 7 origin_str.append(origin_str[i]) 8 origin_str = origin_str[length:] 9 reverse_str = "" 10 for ele in origin_str: 11 reverse_str = reverse_str + ele 12 return reverse_str.strip() 13 s_list = s.split( ) 14 for index in range(0, len(s_list)): 15 s_list[index] = reverseString(s_list[index]) 16 reverse_str = "" 17 for ele in s_list: 18 reverse_str = reverse_str + " " + ele 19 return reverse_str.strip()