1. 程式人生 > >【Leetcode_總結】 917. 僅僅反轉字母 -python

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