write once,run anywhere
  • Home
  • Tags
  • Archives

LeetCode [3] Longest Substring Without Repeating Characters

Contents

  • Questions
  • Coding
    • python

Questions¶

Difficulty: Medium

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.

Coding¶

python¶

# -*- coding: utf-8 -*-
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        dict, ans, p1, p2 = {}, 0, 0, 0
        while p2 < len(s):
            p = dict.get(s[p2], None)
            if p == None:
                dict[s[p2]] = p2
                p2 += 1
                ans = max(ans, p2 - p1)
            else:
                while p1 <= p:
                    dict.pop(s[p1])
                    p1 += 1
                p1 = p + 1
        return ans

Related Posts

  • LeetCode [1] Two Sum
  • LeetCode [2] Add Two Numbers
  • LeetCode [58] Length of Last Word
  • LeetCode [190] Reverse Bits
  • LeetCode [151] Reverse Words in a String

  • « LeetCode [190] Reverse Bits
  • LeetCode [70] Climbing Stairs »

Published

8月 20, 2016

Last Updated

8月 20, 2016

Category

Linux

Tags

  • LeetCode 13

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor