[leetcode] 917. Reverse Only Letters

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值