1. 程式人生 > >4.4.1 python 字串雙指標/雜湊演算法1—— Reverse Vowels of a String & Longest Substring Without Repeating Char

4.4.1 python 字串雙指標/雜湊演算法1—— Reverse Vowels of a String & Longest Substring Without Repeating Char

這一部分開始,我們應用雙指標及雜湊等常見的簡單的演算法,解決一些字串的難題。

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"

Note:
The vowels does not include the letter "y".

題目解析:

雙指標在字串的應用也很簡單,這道題難度也是easy。需要說明的是字串中字元的 交換隻能用切片,下面的程式碼則是先將字串轉為列表後再操作的。

class Solution:
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        i = 0
        j = len(s) - 1
        l = list(s)
        while i < j:
            while not l[i] in "aeiouAEIOU" and i < j:
                i += 1
            while not l[j] in "aeiouAEIOU" and i < j:
                j -= 1
            if i >= j:
                break
            l[i], l[j] = l[j], l[i]
            # s = s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]  # 切片的話這樣寫
            i += 1
            j -= 1
        
        return ''.join(l)

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

題目解析:

與上一題想比,兩個指標都是從頭掃描,在滑動窗內遇到重複的字元,將前面的捨棄掉,並重置n,此時不可能使n增長,所以無需判斷;無重複的則新增增長字串,並判斷是否最長。

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        longest = []
        length_max = 0
        n = 0
        for x in  s:           
            if x in longest:
                ix = longest.index(x)
                longest = longest[(ix+1):]      # 捨棄前面的
                longest.append(x)
                n = len(longest)
                # print(n,longest)
 
            else:
                longest.append(x)
                n += 1
                # print(n, longest)
                if n > length_max:
                    length_max = n
        return length_max