917. 仅仅反转字母
题目要求:
给定一个字符串 S,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。
解题思路:
- 获取原始字符串中的所有字母,顺序保持不变;
- 获取原始字符串中的所有非字母,并记录其位置;
- 反转获取到的子字符串(1)(所有字母);
- 将获取到的非字母(2),按照之前的位置(2),添加进去(3);
- 返回结果。
题解代码:
class Solution:
def reverseOnlyLetters(self, S: str) -> str:
n = len(S)
#获取一个字母数组
word = []
for i in range(65,91):
word.append(chr(i))
word.append(chr(i+32))
#记录非字母的位置,和字母
notwordlocal = []
notword = []
for i in range(n):
if S[i] not in word:
notwordlocal.append(i)
notword.append(S[i])
#将非字母先用一个空格替换
S = S.replace(S[i]," ",1)
#将空格替换,获取一个只包含字母的字符串
S = S.replace(" ","")
#反转字符串(先转化为数组)
ls = list(S)
ls.reverse()
#将非字母字符加入反转后的字符串中
##遍历没有遍历到的非字母字符(a表示非字母字符数组中每个元素的位置)
a = 0
#遍历要插入到反转字符串数组中的位置
for i in notwordlocal:
#遍历非字母字符
for j in range(a,len(notword)):
#插入原本的位置处
ls.insert(i,notword[j])
a +=1
break
#将列表转化为字符串
S = ''.join(ls)
return S
(“Storms make trees take deeper roots.(越是经历风暴,数目扎根越深。)
”FIGHTING. . . .)