【LeetCode】仅仅反转字母

题目描述

给你一个字符串 s ,根据下述规则反转字符串:

所有非英文字母保留在原有位置。 所有英文字母(小写或大写)位置反转。 返回反转后的 s 。

示例

示例 1:

输入:s = “ab-cd” 输出:“dc-ba” 示例 2:

输入:s = “a-bC-dEf-ghIj” 输出:“j-Ih-gfE-dCba” 示例 3:

输入:s = “Test1ng-Leet=code-Q!” 输出:“Qedo1ct-eeLg=ntse-T!”

方法

记录非字母的位置,然后逆序不包含非字母的字符串,最后利用for循环插入非字母。

代码

class Solution:
    def reverseOnlyLetters(self, s: str) -> str:
        dictionary = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        news = ""
        nondict = []
        for i in range(len(s)):
            if s[i] not in dictionary:
                nondict.append(i)
            else:
                news += s[i]
        news = news[::-1]
        for i in nondict:
            news = news[:i] + s[i] + news[i:]
        return news
经验分享 程序员 微信小程序 职场和发展