Find longest substring without repeating characters

前端 未结 30 2550
轻奢々
轻奢々 2020-12-12 18:07

Given a string S of length N find longest substring without repeating characters.

Example:

Input:

30条回答
  •  生来不讨喜
    2020-12-12 18:51

    This problem can be solved in O(n) time complexity. Initialize three variables

    1. Start (index pointing to the start of the non repeating substring, Initialize it as 0 ).
    2. End (index pointing to the end of the non repeating substring, Initialize it as 0 )
    3. Hasmap (Object containing the last visited index positions of characters. Ex : {'a':0, 'b':1} for string "ab")

    Steps : Iterate over the string and perform following actions.

    1. If the current character is not present in hashmap (), add it as to hashmap, character as key and its index as value.
    2. If current character is present in hashmap, then

      a) Check whether the start index is less than or equal to the value present in the hashmap against the character (last index of same character earlier visited),

      b) it is less then assign start variables value as the hashmaps' value + 1 (last index of same character earlier visited + 1);

      c) Update hashmap by overriding the hashmap's current character's value as current index of character.

      d) Calculate the end-start as the longest substring value and update if it's greater than earlier longest non-repeating substring.

    Following is the Javascript Solution for this problem.

    var lengthOfLongestSubstring = function(s) {
        let length = s.length;
        let ans = 0;
        let start = 0,
            end = 0;
        let hashMap = {};
    
        for (var i = 0; i < length; i++) {
    
            if (!hashMap.hasOwnProperty(s[i])) {
                hashMap[s[i]] = i;
            } else {
                if (start <= hashMap[s[i]]) {
                    start = hashMap[s[i]] + 1;
                }
                hashMap[s[i]] = i;
            }
            end++;
            ans = ans > (end - start) ? ans : (end - start);
        }
        return ans;
    };
    

提交回复
热议问题