LeetCode 917 Reverse Only Letters 解题报告

时间:2019-03-15
本文章向大家介绍LeetCode 917 Reverse Only Letters 解题报告,主要包括LeetCode 917 Reverse Only Letters 解题报告使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目要求

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.

题目分析及思路

给定一个字符串,返回“reversed”后的字符串,要求非字母的字符保留原来的位置,字母字符逆序排列。可以先获得原字符串中的全部字母字符列表,然后遍历原字符串,并用一个新的列表存储结果。若某位置是字母字符,就取先前获得的列表中的末尾元素;若是非字母字符,则保留该位置的字符。最后将列表转换成字符串。

python代码

class Solution:

    def reverseOnlyLetters(self, S: str) -> str:

        letters = [c for c in S if c.isalpha()]

        res = []

        for c in S:

            if c.isalpha():

                res.append(letters.pop())

            else:

                res.append(c)

        return "".join(res)