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:
- S.length <= 100
- 33 <= S[i].ASCIIcode <= 122
- 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