[leetcode] 917. Reverse Only Letters @ python

原题

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 "

解法1

先将S中的字母放入列表ans里, 然后记录S中非字母的索引和字符, 再遍历non_letters, 将非字母的字符插入ans中, 最后将ans转化为字符串.
Time: 3*O(n)
Space: O(1)

代码

class Solution(object):
    def reverseOnlyLetters(self, S):
        """
        :type S: str
        :rtype: str
        """
        ans = [char for char in S if char.isalpha()][::-1]
        # get the index and char of non-letters
        non_letters = [(i, char) for i, char in enumerate(S) if not char.isalpha()]
        for i, char in non_letters:
            ans.insert(i, char)
        return ''.join(ans)

解法2

双指针法, 定义左右两个指针, 从左右两边往中间刷, 遇到字母时, 两个字母交换.
Time: O(n)
Space: O(1)

代码

class Solution(object):
    def reverseOnlyLetters(self, S):
        """
        :type S: str
        :rtype: str
        """
        l, r = 0, len(S)-1
        s = list(S)
        while l < r:
            while l < r and not S[l].isalpha():
                l += 1
            while l < r and not S[r].isalpha():
                r -= 1
            # swap two letters
            s[l], s[r] = s[r], s[l]
            l += 1
            r -= 1
        return ''.join(s)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值