https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入: "Let's take LeetCode contest" 输出: "s'teL ekat edoCteeL tsetnoc" 注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
坨坨的解法:
解法一
s = "Let's take LeetCode contest"
sentence = ''
word = ''
for i in s:
if i != " ":
word += i
else:
word = word[::-1]
word += ' '
sentence += word
word = ''
sentence += word[::-1] # 最后一个特殊处理
print(sentence)
解法二
#解法二
s = "Let's take LeetCode contest"
word_ls = s.split(' ')
for i in range(len(word_ls)):
word_ls[i] = word_ls[i][::-1]
s = " ".join(word_ls)
print(s)
错误集锦:
s = "Let's take LeetCode contest"
word_ls = s.split(' ')
for word in word_ls:
word = word[::-1] # 字符串不能改变!!!
print(word_ls) # 竟然没变!!!
输出:
["Let's", 'take', 'LeetCode', 'contest']
改错:
# 针对上面,改进,此解法也是Leecode上效率最高的解法
s = "Let's take LeetCode contest"
ls = s.split(' ')
for i,word in enumerate(ls):
word = word[::-1]
ls[i] = word
print(' '.join(ls))
Leecode牛逼解法
解法一 (见上面错误改进)
解法二
# 先元素反转,再拼接成字符串,再整体反转
s = "Let's take LeetCode contest"
print(" ".join((s.split(' ')[::-1]))[::-1])
解法三
# 先split出一个列表,额外建一个空列表,把每个反转好的元素添加进新列表,再对新列表拼接成字符串
s = "Let's take LeetCode contest"
ls = s.split()
new_ls = []
for word in ls:
new_ls.append(word[::-1])
print(' '.join(new_ls))
解法四
# 列表推导式方式,实现解法三的逻辑
s = "Let's take LeetCode contest"
print(" ".join([x[::-1] for x in s.split(' ')]))
解法五(见坨坨的解法二)
总结
- 建立转化成列表处理的意识
- 牢记split和join函数,是针对字符串的可逆操作
- 列表可改变(通过索引元素),但字符串不可改变(会创建新的变量)
- for循环,a.直接循环列表元素,b.序号循环,遍历列表长度(range(len(ls))),c.序号和元素同时循环,enumerate(ls)
- 列表推导式可代替简单的for循环
本地Notebook链接: