题目

917. Reverse Only Letters(反转列表)

我的代码

class Solution(object):
    def reverseOnlyLetters(self, S):
        """
        :type S: str
        :rtype: str
        """
        i=0
        j=len(S)-1
        S=list(S)
        while i<j:
            if not S[i].isalpha():
                i+=1
                continue;
            if not S[j].isalpha():
                j-=1
                continue
            t=S[i]
            S[i]=S[j]
            S[j]=t
            i+=1
            j-=1
        return ''.join(S)

优秀代码

其中间,用了while效率更高一些。

class Solution(object):
    def reverseOnlyLetters(self, S):
        """
        :type S: str
        :rtype: str
        """
        s = []
        i = 0
        j = len(S) -1
        for i, x in enumerate(S):
            if x.isalpha():
                while not S[j].isalpha():
                #i +=1
                    j-=1
                s.append(S[j])
                j -=1
                
            else:
                s.append(x)
        return "".join(s)

相关文章:

  • 2021-09-17
  • 2022-12-23
  • 2021-04-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-17
猜你喜欢
  • 2021-08-05
  • 2021-11-18
  • 2022-12-23
  • 2021-11-13
  • 2021-08-25
  • 2021-11-28
  • 2021-12-15
相关资源
相似解决方案