leetcode-03 characters without repeating the longest substring

Code solution to a problem

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        length = len(s)
        res = 0
        count = 0
        for i in range(length):
            count = 1
            dic = {s[i]: 1}
            for j in range(i + 1, length):
                if dic.get(s[j], 0):
                    res = max(res, count)
                    break
                else:
                    count += 1
                    dic[s[j]] = 1
            else:
                res = max(res, count)
            if res > length - i:
                return res
        return max(res, count)

First, the overall analysis

1. The title medium difficulty, to find the longest string in the letter string does not contain repeated (continuous).

2 may first be conceivable to use brute force way that loops through character s, find the length of the longest string of non-repetitive characters to each character of the resultant led,

    Then returns the maximum string length of the longest of all non-repeating characters corresponding to the character.

 

Second, the specific practices

1. res variable length storage longest string of non-repetition, each iteration update it, avoiding lengthy storage in all the characters, led by a unique string without causing waste of space and time.

2. The length of the current variable count is calculated in the character currently available headed configuration of the non-repeating string (by the variable update 2 cyclic).

3. dic a variable dictionary, to compare the current portion of the resultant 2 cyclic whether the character can be traversed before and combined to constitute a character string without duplication,

    If the current character is already present inside the dic, it indicates that the character has occurred before, the loop should be terminated immediately, the current value of count that is led to the length of the longest character string can not duplicate configuration,

    Followed by a traverse to the next character, re-initialize the count and dic.

 

Guess you like

Origin www.cnblogs.com/DreamDoom/p/Answer03.html