Write a C# Sharp program to find the length of the longest substring without repeating characters from a given string


Write a C# Sharp program to find the length of the longest substring without repeating characters from a given string.

Expected Output :

Original String: aaaaaabbbbccc
Length of the longest substring without repeating characters of the said string:
2
Original String: BDEFGAABEF
Length of the longest substring without repeating characters of the said string:
6
Original String: Python
Length of the longest substring without repeating characters of the said string:
6
Original String: Java
Length of the longest substring without repeating characters of the said string:
3

الأجوبة

ابحث عن مسائل برمجة سي شارب | c# programming بالانجليزي

using System;
using System.Collections.Generic;
namespace exercises
{
     class Program
    {
        static void Main(string[] args)
        {
            String str1;
            str1="aaaaaabbbbccc";
            Console.WriteLine("Original String: "+str1);
            Console.WriteLine("Length of the longest substring without repeating characters of the said string:");
            Console.WriteLine(without_repeated_chars_longest_substring(str1));
            str1="BDEFGAABEF";
            Console.WriteLine("Original String: "+str1);
            Console.WriteLine("Length of the longest substring without repeating characters of the said string:");;
            Console.WriteLine(without_repeated_chars_longest_substring(str1));
            str1="Python";
            Console.WriteLine("Original String: "+str1);
            Console.WriteLine("Length of the longest substring without repeating characters of the said string:");
            Console.WriteLine(without_repeated_chars_longest_substring(str1));
            str1="Java";
            Console.WriteLine("Original String: "+str1);
            Console.WriteLine("Length of the longest substring without repeating characters of the said string:");
            Console.WriteLine(without_repeated_chars_longest_substring(str1));
        }
     public static int without_repeated_chars_longest_substring(string str1)
        {
              if (string.IsNullOrEmpty(str1)) return 0;
            var map_str = new Dictionary<int, int>();
            var max_len = 0;
            var last_repeat_pos = -1;
            for (int i = 0; i < str1.Length; i++)
            {
                if (map_str.ContainsKey(str1[i]) && last_repeat_pos < map_str[str1[i]])
                    last_repeat_pos = map_str[str1[i]];
                if (max_len < i - last_repeat_pos)
                    max_len = i - last_repeat_pos;
                map_str[str1[i]] = i;
            }
            return max_len;
        }
  }
}

محتاج مساعدة؟ تواصل مع مدرس اونلاين الان!