[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

使用字典来储存符合条件的子字符串, 当遇到重复的字母时, 更新起始点start, 每次迭代时更新结果, 更新字典.
Time: O(n)
Space: O(1)

代码

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        d, start, res = {}, 0, 0
        for i, c in enumerate(s):
            if c in d:
                # update the start index
                start = max(start, d[c]+1)
            # update the res
            res = max(res, i-start+1)
            # update the dict
            d[c] = i
            
        return res

解法2

双指针法, 用left, right两个指针, 用子字符串的长度是否等于集合的长度来判断是否有重复字符串, 如果没有重复字符串, 则更新res并且right指针向前走一步, 如果存在重复字符串, 则left, right指针都向前走一步.
Time: O(n)
Space: O(1)

代码

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        # base case
        if not s: return 0
        if len(s) == 1: return 1
        res = 1
        left, right = 0, 1
        while right <= len(s)-1:
            sub = s[left:right+1]
            if len(sub) == len(set(sub)):                
                res = max(res, right-left+1)
                right += 1
            else:
                left += 1
                right += 1
                
        return res

你可能感兴趣的:(Leetcode)