LeetCode:3. Longest Substring Without Repeating Characters

来源:互联网 发布:ui需要什么类编程 编辑:程序博客网 时间:2024/06/07 12:12

原文链接

Question

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.

My Solution

Notice: There’re several typical cases you should pay attention to.

  1. Only one character exists.(Like ‘a’)
  2. No repeating character.(Like ‘abc’)

Train of thought:

I use two variables:temporal_result and final_result.

When a new character is found, it is appended to temporal_result. Check whether the length of final_result is smaller than that of temporal_result, and if so, final_result refers to temporal_result.

After processing all characters, we return the longer one between temporal_result and final_result in case of the last character being a totally new one.

class MySolution(object):    def lengthOfLongestSubstring(self, s):        """        :type s: str        :rtype: int        """        temporal_result = ''        final_result = ''        for character in s:            if character not in temporal_result:                temporal_result += character            else:                if len(final_result) < len(temporal_result):                    final_result = temporal_result                index = temporal_result.index(character)                temporal_result = temporal_result[index+1:] + character        if len(temporal_result) > len(final_result):            return len(temporal_result)        else:            return len(final_result)

Editorial Solution of LeetCode

Approach One: Brute force [Time Limit Exceeded]

Train of thought:

Check every possible subtring, so it’s time complexity is rather high(O(n3)).

Approach Two: Sliding Window

Train of thought:

Use HashSet to store the characters in current window [i, j)(j=i initially). Then slide the index j to the right. If it is not in the HashSet, slide j further. Doing so until s[j] is already in the HashSet. At this point, we found the maximum size of substrings without duplicate characters start with index i. If we do this for all i, we get our answer.

Approach Three: Sliding Window Optimized

Train of thought:

The approach has some commons with my solution. It updates the index of repeated character while mine keeps the initial index of the character when it is found, which means approach three tracks the latest longest substring and my solution gets the longest substring found earliest if there are at least two substrings with equal length (case like ‘abcda’, approach three gets ‘bcda’ and my method gets ‘abcd’).

0 0
原创粉丝点击