【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.

class Solution(object):

    def reverseOnlyLetters(self, S):

        """

        :type S: str

        :rtype: str

        """

        if not S: return S

        S = list(S)

        i, j = 0, len(S)-1

        while i

            while i

                i += 1

            while i

                j -= 1

            S[i], S[j] = S[j], S[i]

            i += 1

            j -= 1

        return ''.join(S)

1 使用双指针方法,一个从最前,一个从最后,只要是字母,就swap

2 while i

3 字符串是不可变对象,不能通过下标进行赋值。所以此题中先将s转换成list,等操作完以后,再通过‘’.join(S)转换成字符串

你可能感兴趣的:(【Leetcode】917. Reverse Only Letters)