4.4.1 python 字符串双指针/哈希算法1—— Reverse Vowels of a String & Longest Substring Without Repeating Char

这一部分开始,我们应用双指针及哈希等常见的简单的算法,解决一些字符串的难题。

345. Reverse Vowels of a String

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)

3. Longest Substring Without Repeating Characters(最长无重复字符子串)

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

猜你喜欢

转载自blog.csdn.net/xutiantian1412/article/details/84000708