Longest substring without repeating characters

Given a string, write a program to find the length of the longest substring without repeating characters.


For Example

Innput:
 Str = abcabcbb 

Output:
3

Longest substring can be frame from give string is abc

Solution:

using System;
using System.Collections.Generic;

namespace LongSubString
{
    class Program
    {
        public static void Main()
        {
            var ss = LongestSubstringLen("iaahessheaa");
            Console.ReadLine();
        }

        static int LongestSubstringLen(string s)
        {
            var res = 0;
            var dict = new Dictionary<char,int>();
            var start = 0;

            for (var i = 0; i < s.Length; i++)
            {
                if (dict.ContainsKey(s[i]))
                {
                    start = Math.Max(start, dict[s[i]] + 1);
                    dict[s[i]] = i;
                }
                else
                {
                    dict.Add(s[i], i);
                }

                res = Math.Max(res, i - start + 1);
            }

            return res;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *