3. Longest Substring Without Repeating Characters

# -*- coding: utf-8 -*-
'''
3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring 
without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.
'''

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start = max_len = 0
        used_char = {}
        
        for i in range(len(s)):
            if s[i] in used_char and start <= used_char[s[i]]:
                start = used_char[s[i]] + 1
            else:
                max_len = max(max_len, i - start + 1)

            used_char[s[i]] = i
        return max_len

if __name__ == '__main__':
    tests = ['abcabca', 'bbbbb', 'pwwekw', 'abcbefg']
    solution = Solution()
    for s in tests:
        solution.lengthOfLongestSubstring(s)

你可能感兴趣的:(3. Longest Substring Without Repeating Characters)