Leetcode 3 - Longest Substring Without Repeating Characters

Problem 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.

Java:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        char[] cs = s.toCharArray();
        HashMap map = new HashMap<>();
        int maxLen = 0;
        
        for (int i = 0, pi = -1; i < cs.length; i++) {
            if (map.containsKey(cs[i])) {
                int preCI = map.get(cs[i]);
                while(++pi < preCI) {
                    map.remove(cs[pi]);
                }
            }
            map.put(cs[i], i);
            maxLen = Math.max(i - pi, maxLen);
        }
        return maxLen;
    }
}

Python:

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {}
        maxLen, pi = 0, -1
        
        for i, c in enumerate(s):
            if dic.get(c, -1) != -1:
                preCI = dic[c]
                while pi < preCI:
                    pi += 1
                    dic[pi] = -1
                    
            dic[c] = i
            maxLen = max(maxLen, i - pi)

        return maxLen

Go:

func lengthOfLongestSubstring(s string) int {
    dic := make(map[rune]int)
    cs := []rune(s)
    pi, maxLen := -1, 0
    
    for i, c := range(cs) {
        if pci, ok := dic[c]; ok {
            for pi < pci {
                pi++
                delete(dic, cs[pi])
            }
        }
        dic[c] = i
        if i - pi > maxLen {
            maxLen = i - pi
        }
    }
        
    return maxLen
}

你可能感兴趣的:(Leetcode 3 - Longest Substring Without Repeating Characters)