Skip to content

[3] Longest Substring Without Repeating Characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

  • algorithms
  • Medium (25.39%)
  • Source Code: 3.longest-substring-without-repeating-characters.py
  • Total Accepted: 878.7K
  • Total Submissions: 3.1M
  • Testcase Example: '"abcabcbb"'

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.

python
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        length = len(s)
        i, j = 0, 0
        arr = [0] * 256
        mx = 0
        while i < length and j < length:
            # print('i, j', i, j, s, s[i], s[j])
            if arr[ord(s[j])] == 0:
                arr[ord(s[j])] = 1
                j += 1
                mx = j - i if j - i > mx else mx
            else:
                arr[ord(s[i])] = 0
                i += 1
        return mx


# if __name__ == '__main__':
#     s = Solution()
#     print s.lengthOfLongestSubstring('pwwkew')

Last updated: