C# LengthOfLongestSubstring


  • 0
    L

    public class Solution {
    public int LengthOfLongestSubstring(string s) {
    if (s == string.Empty) return 0;
    int maxLength = 0;
    int curLength = 0;
    Dictionary<char, int> dc = new Dictionary<char, int>();
    int i=0;
    int tempIndex = 0;

        while (i < s.Length)
        {
            if (dc.ContainsKey(s[i]))
            {
                if (tempIndex <= dc[s[i]])
                {
                    tempIndex = dc[s[i]];
                    curLength = i - tempIndex;
                }
                else
                {
                    curLength++;
                }
                
                dc[s[i]] = i;
            }
            else
            {
                dc.Add(s[i], i);
                curLength++;
            }
            
            if (maxLength < curLength) maxLength = curLength;
            i++;
        }
    
        return maxLength;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.