3. Longest Substring Without Repeating Characters
Posted Premiumlab
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3. Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description
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.
Sol:
Instead of using a set to tell if a character exists or not, we could define a mapping of the characters to its index. Then we can skip the characters immediately when we found a repeated character.
The reason is that if s[j] have a duplicate in the range [i, j) with index j‘, we don‘t need to increase iilittle by little. We can skip all the elements in the range [i, j‘] and let ii to be j‘ + 1 directly.
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ # Using HashMap # Time O(n) n = len(s) ans = 0 # map stores the index of the current element map = collections.defaultdict(int) # try to extend to the range[i, j] i = 0 for j in range(n): if s[j]: i = max(i, map[s[j]]) ans = max(ans, j - i + 1) map[s[j]] = j + 1 return ans
以上是关于3. Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章
longest-substring-with-at-least-k-repeating-characters
LeetCode 395. Longest Substring with At Least K Repeating Characters
395. Longest Substring with At Least K Repeating Characters
3. Longest Substring Without Repeating Characters
Leetcode: Longest Substring with At Least K Repeating Characters