Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

longest substring without repeating characters c#

public class Solution 
{
    public int LengthOfLongestSubstring(string str) 
    {
        var dict = new Dictionary<char, int>();
        var max = 0;
        int start = 0;
        for (int i = 0; i < str.Length; i++)
        {
            var x = str[i];
            if (!dict.ContainsKey(x))
            {
                dict.Add(x, 1);
            }
            else
            {
                dict[x] += 1;
                while (start <= i && dict.ContainsKey(str[start]) && dict[x] > 1)
                {
                    dict[str[start]]--;
                    if (dict[str[start]] == 0)
                        dict.Remove(str[start]);
                    start++;
                }
            }
            max = Math.Max(max, i - start + 1);
        }
        return max;
    }
}
Source by leetcode.com #
 
PREVIOUS NEXT
Tagged: #longest #substring #repeating #characters
ADD COMMENT
Topic
Name
1+2 =