Find longest substring without repeating characters

前端 未结 30 2576
轻奢々
轻奢々 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: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();
        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);
    }
    

提交回复
热议问题