LeetCode 3. Longest Substring Without Repeating

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 3. Longest Substring Without Repeating相关的知识,希望对你有一定的参考价值。

鏍囩锛?/p>

 

棰樼洰锛?/p>

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

 

鎬濊矾锛?/p>

鐢ㄤ竴涓猰ap瀛樻斁瀛楃鍑虹幇鐨刾osition锛涚敤涓や釜鎸囬拡begin,end鎸囧悜substr鐨勯鏈紱閬囧埌鐩稿悓瀛楃鏃跺皢begin绉诲埌璇ュ瓧绗︿箣鍓嶅嚭鐜扮殑鍚庝竴浣嶇疆锛屽苟鏇存柊璇ュ瓧绗︾殑position銆?/p>

 

浠g爜锛欳++ :

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.length() <= 1)
            return s.length();
        
        int begin = 0;
        int end = 0;
        map<char,int> mapping;
        int solve = 0;
        
        mapping[s[0]] = 0;
        while (end < s.length() - 1) {
            end++;
           if (mapping.find(s[end]) != mapping.end()) {
                int gap = end - begin;
                if (gap > solve)
                    solve = gap;
                begin = mapping[s[end]] + 1 > begin ? mapping[s[end]] + 1 : begin;
                mapping[s[end]] = end;
            }
            else
                mapping[s[end]] = end;
        }
        int gap = end - begin + 1;
        if (gap > solve)
            solve = gap;
        return solve;
    }
};

 

以上是关于LeetCode 3. Longest Substring Without Repeating的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 3. Longest Substring Without Repeating Characters

LeetCode 3. Longest Substring Without Repeating

3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]

3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]

leetcode longest consecutive sequence

leetcode 3. Longest Substring Without Repeating Characters (Python版)