【2019.07.25 Python每日一题】答案 —— 反转字符串中的单词 III 【Leecode557】

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(' ')]))

解法五(见坨坨的解法二)

总结

  1. 建立转化成列表处理的意识
  2. 牢记split和join函数,是针对字符串的可逆操作
  3. 列表可改变(通过索引元素),但字符串不可改变(会创建新的变量)
  4. for循环,a.直接循环列表元素,b.序号循环,遍历列表长度(range(len(ls))),c.序号和元素同时循环,enumerate(ls)
  5. 列表推导式可代替简单的for循环

本地Notebook链接:

http://localhost:8888/notebooks/notebooks/Python123/%E3%80%90%E6%AF%8F%E6%97%A5%E4%B8%80%E9%A2%98%E3%80%91/%E3%80%902019.07.25%20Python%E6%AF%8F%E6%97%A5%E4%B8%80%E9%A2%98%E3%80%91%E2%80%94%E2%80%94%20%E5%8F%8D%E8%BD%AC%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E7%9A%84%E5%8D%95%E8%AF%8D%20III%20%E3%80%90Leecode557%E3%80%91.ipynb

 

 

 

上一篇:C#随机挑选某一个用户或者几个用户信息


下一篇:Array.Copy vs Skip and take in c#