【Leetcode_总结】 917. 仅仅反转字母 -python

Q:

给定一个字符串 S,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。

示例 1:

输入:"ab-cd"
输出:"dc-ba"

示例 2:

输入:"a-bC-dEf-ghIj"
输出:"j-Ih-gfE-dCba"

思路:双指针,分别从字符串两侧向中间遍历,判断是否是字母,如果是,交换两个字符

class Solution:
    def reverseOnlyLetters(self, S):
        """
        :type S: str
        :rtype: str
        """
        temp = [i for i in S]
        left = 0
        right = len(temp)-1
        while(left < right):
            if self.isword(temp[left]):
                if self.isword(temp[right]):
                    temp[left],temp[right] = temp[right],temp[left]
                    left += 1
                    right -= 1
                else:
                    right-=1
            else:
                left+=1
        return (''.join(temp))
    
    def isword(self,w):
        if ord(w) >= ord('a') and ord(w) <= ord('z') or (ord(w) >= ord('A') and ord(w) <= ord('Z')):
            return True
        else:
            return False

使用内置函数 isalpha() 发现效率并不是很好,代码如下: 

class Solution:
    def reverseOnlyLetters(self, S):
        """
        :type S: str
        :rtype: str
        """
        temp = [i for i in S]
        left = 0
        right = len(temp)-1
        while(left < right):
            if temp[left].isalpha():
                if temp[right].isalpha():
                    temp[left],temp[right] = temp[right],temp[left]
                    left += 1
                    right -= 1
                else:
                    right-=1
            else:
                left+=1
        return (''.join(temp))

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值