How to find the length of the longest substring from the given string without repeating the characters using C#?


From the given string input, use the sliding window technique by having 2 pointers i and j . both i and j will point to the same character in the string. Traverse through the string and add it to the list. If the repeated character is found then remove it from the list else append to the list.

Example 1

Input − s = "abcabcbb"

Output − 3

Explanation − The answer is "abc", with the length of 3.

Example 2

Input − s = "bbbbb"

Output − 1

Explanation − The answer is "b", with the length of 1.

Time complexity − O(N)

Space complexity − O(N)

Example

public class Arrays{
   public int LongestSubstringWithNoRepeatingCharacters(string s){
      List<char> c = new List<char>();
      int iPointer = 0;
      int jpointer = 0;
      int max = 0;
      while (jpointer < s.Length){
         if (c.Contains(s[jpointer])){
            c.Remove(s[iPointer]);
            iPointer++;
         }
         else{
            max = Math.Max(c.Count(), max);
            c.Add(s[jpointer]);
            jpointer++;
         }
      }
      return max;
   }
}

static void Main(string[] args){
   int res = s.LongestSubstringWithNoRepeatingCharacters("abcabcbb");
   Console.WriteLine(res);
}

Output

2

Updated on: 17-Aug-2021

900 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements