LeetCode | 算法:字符串匹配、最长无重复字符子串长度

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.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
笔记:
类似第1题的思路,但是这里使用列表代替字典,记录当前找到的无重复字符。用列表的好处是它是有序的,且支持随机访问。

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        max_len = 0      # 记录已找到的最大无重复字符长度
        str_set = []     # 记录当前找到的无重复字符
        
        for _,string in enumerate(s):
            if string in str_set:
                # 先看看是否更新最长子串长度
                if len(str_set) > max_len:
                    max_len = len(str_set)
                    
                # 删掉之前的那个及其前面的字符,并更新现在的这个
                str_set = str_set[str_set.index(string)+1:]
                str_set.append(string)
            
          else:
                str_set.append(string)
        
        if len(str_set) > max_len:
            max_len = len(str_set)

        return max_len

28. Implement strStr()

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
笔记:
采用了简单匹配算法
改进:KMP算法

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        n = len(needle)
        
        if n == 0:
            return 0
        
        for i in range(len(haystack) - n + 1):
            if haystack[i:i+n] == needle:
                return i
            
        return -1
  

你可能感兴趣的:(LeetCode | 算法:字符串匹配、最长无重复字符子串长度)