LeetCode: 3. Longest Substring Without Repeating Characters

No.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”, which the length is 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.

Solution one(by myself):

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        longest_substring = []
        count_max = 0
        if len(s) == 1 or len(s) == 0:
            count_max = len(s)
        for count_item in s:
            if count_item not in longest_substring:
                longest_substring.append(count_item)
            else:
                count_max = max(len(longest_substring), count_max)
                del_count = 0
                i = 0
                for del_item in longest_substring:
                    if del_item != count_item:
                        del_count += 1
                    else:
                        del_count += 1
                        break
                longest_substring = longest_substring[del_count:]
                longest_substring.append(count_item)
        count_max = max(len(longest_substring), count_max)
        return count_max

Reference solution:

def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        #创建一个空字典,其存放的形式是“单字符:出现位置的索引”
        indexDict = {}
        #存放记录最大长度和当前循环下的长度
        maxLength = currMax = 0
        for i in range(len(s)):
            #这里是关键,小詹看了挺久的,小伙伴们比我强,应该比较快
            #这里是当s[i]没有在之前出现过,则当前长度currMax自动加一
            #当出现了重复字符,则比较当前找到的子字符串长度和历史最大长度
            #重点是这里i - indexDict[s[i]] - 1 的含义;代码后举例具体讲解
            if s[i] in indexDict and i - indexDict[s[i]] - 1 <= currMax:
                if maxLength < currMax:
                    maxLength = currMax
                currMax = i - indexDict[s[i]] - 1
            currMax = currMax + 1                
            indexDict[s[i]] = i 
        return maxLength if currMax < maxLength else currMax

代码里对应位置加入了注释,理解起来应该好很多了,这里举例说明下为什么【i - indexDict[s[i]] - 1】代表了当前找到子字符串的长度。

比如字符串’abcdadd’,代码运行过程中一直迭代到i=3【对应字符d】时,都不满足s[i] in indexDict ,不执行条件语句,而是currMax依次加一,并且将字符信息以{s[i]:i}的形式存放在字典中。当继续迭代i=4时,进入条件语句,这里主要解释【i - indexDict[s[i]] - 1】,检测到了重复字符’a’,之前该字符出现位置为i=0处即【indexDict[s[i]] =0】这时候当前检测到的无重复字符子串为’abcd’,长度为【4-indexDict[s[i]] -1 = 3】。其他同此例。

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/82027450