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

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值