Find longest substring without repeating characters

前端 未结 30 2244
轻奢々
轻奢々 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;
    };
    
    0 讨论(0)
  • 2020-12-12 18:51
    public int lengthOfLongestSubstring(String s) {
        int startIndex = 0;
        int maxLength = 0;
        //since we have 256 ascii chars
        int[] lst = new int[256];
        Arrays.fill(lst,-1);
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            //to get ascii value of c
            int ic = (int) c;
            int value = lst[ic];
            //this will say to move start index to next index of the repeating char
            //we only do this if the repeating char index is greater than start index
            if (value >= startIndex) {
                maxLength = Math.max(maxLength, i - startIndex);
                startIndex = value + 1;
            }
            lst[ic] = i;
        }
        //when we came to an end of string
        return Math.max(maxLength,s.length()-startIndex);
    }
    

    This is the fastest and it is linear time and constant space

    0 讨论(0)
  • 2020-12-12 18:53

    I modified my solution to "find the length of the longest substring without repeating characters".

            public string LengthOfLongestSubstring(string s) {
        var res = 0;
        var dict = new Dictionary<char, int>();
        var start = 0;
    
        for(int i =0; i< s.Length; i++)
        {
            if(dict.ContainsKey(s[i]))
            {
                start = Math.Max(start, dict[s[i]] + 1); //update start index
                dict[s[i]] = i;
            }
            else
            {
                dict.Add(s[i], i);
            }
    
            res = Math.Max(res, i - start + 1);  //track max length
        }
        return s.Substring(start,res);
    }
    
    0 讨论(0)
  • 2020-12-12 18:53

    can we use something like this .

    def longestpalindrome(str1):
        arr1=list(str1)
        s=set(arr1)
        arr2=list(s)
        return len(arr2)
    
    
    
    str1='abadef'
    a=longestpalindrome(str1)
    print(a)
    

    if only length of the substring is to be returned

    0 讨论(0)
  • 2020-12-12 18:54

    Here is one more solution with only 2 string variables:

    public static String getLongestNonRepeatingString(String inputStr){
        if(inputStr == null){
            return null;
        }
    
        String maxStr = "";
        String tempStr = "";
        for(int i=0; i < inputStr.length(); i++){
            // 1. if tempStr contains new character, then change tempStr  
            if(tempStr.contains("" + inputStr.charAt(i))){
                tempStr = tempStr.substring(tempStr.lastIndexOf(inputStr.charAt(i)) + 1);
            }
            // 2. add new character
            tempStr = tempStr + inputStr.charAt(i);
            // 3. replace maxStr with tempStr if tempStr is longer
            if(maxStr.length() < tempStr.length()){
                maxStr = tempStr;
            }
        }
    
        return maxStr;
    }
    
    0 讨论(0)
  • 2020-12-12 18:54
    private static string LongestSubstring(string word)
            {
                var set = new HashSet<char>();
                string longestOverAll = "";
                string longestTillNow = "";
    
                foreach (char c in word)
                {
                    if (!set.Contains(c))
                    {
                        longestTillNow += c;
                        set.Add(c);
                    }
                    else
                    {
                        longestTillNow = string.Empty;
                    }
    
                    if (longestTillNow.Length > longestOverAll.Length)
                    {
                        longestOverAll = longestTillNow;
                    }
                }
    
                return longestOverAll;
            }
    
    0 讨论(0)
提交回复
热议问题