天天看點

力扣(leetcode) 344. 反轉字元串 345. 反轉字元串中的元音字母 (雙指針法)

兩道題目連結:​​https://leetcode-cn.com/problems/reverse-string/​​​​https://leetcode-cn.com/problems/reverse-vowels-of-a-string/​​

思路分析:

兩道題目所用方法一樣。

我們設定兩個指針,頭和尾,普通翻轉字元串則直接交換頭尾元素,然後兩指針往中間移動。

當頭尾指針重合(奇數個元素情況),或者頭指針下一個是尾指針(偶數個元素情況)時 停止。

完整代碼:

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """ 
        n = len(s)
        i = 0
        j = n-1
        while True:
            s[i] ,s[j] = s[j] ,s[i]
            if i == j or i + 1 == j:
                break
            i += 1
            j -= 1      
class Solution:
    def reverseVowels(self, s: str) -> str:
        s = list(s)
        temp = ['a','e','i','o','u','A','E','I','O','U']
        i = 0
        j = len(s) - 1
        while True:
            if s[i] in temp and s[j] in temp:
                s[i] ,s[j] = s[j] ,s[i]
                i +=1
                j -=1
            elif s[i] not in temp and s[j] not in temp:
                i +=1
                j -=1
            elif s[i] not in temp and s[j] in temp:
                i +=1
            elif s[i] in temp and s[j] not in temp:
                j -=1
            if i >= j:
                break
        print(s)
        return ''.join(s)