0
点赞
收藏
分享

微信扫一扫

[leetcode] 917. Reverse Only Letters

栖桐 2022-08-12 阅读 35


Description

Given a string S, return the “reversed” string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

Example 1:

Input: "ab-cd"
Output: "dc-ba"

Example 2:

Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

Note:

  1. S.length <= 100
  2. 33 <= S[i].ASCIIcode <= 122
  3. S doesn’t contain \ or "

分析

题目的意思是:只将字符串中字母部分进行翻转,其它保持不变。思路也很直接,翻转之后,原位置相应有字母的位置填上翻转的字符就行了。我看了一下答案,用了栈,其他思路基本一致。

代码

class Solution:
def solve(self,ch):
if((ch>='a' and ch<='z') or (ch>='A' and ch<='Z')):
return True
return False

def reverseOnlyLetters(self, S: str) -> str:
n=len(S)
S1=list(reversed(S))
i=0
j=0
res=''
while(i<n):
if(self.solve(S[i])):
while(not self.solve(S1[j])):
j+=1
res+=S1[j]
j+=1
else:
res+=S[i]
i+=1
return res

参考文献

​​[LeetCode] Solution​​


举报

相关推荐

0 条评论