How to find the longest substring without repeating characters in C#

1 Answer

0 votes
using System;
 
public class Program
{
    private static void findLongestSubstringWithoutRepeatingCharacters(string str) {
        int str_size = str.Length;
        int start = 0, end = 0;
        int start_sub = 0, end_sub = 0;
        int[] ASCII = new int[256];
 
        while (end < str_size) {
            if (ASCII[str[end]] > 0) {
                while (str[start] != str[end]) {
                    ASCII[str[start]] = 0;
                    start++;
                }
                start++;
            }
            else {
                ASCII[str[end]] = end + 1;
                if (end - start > end_sub - start_sub) {
                    start_sub = start;
                    end_sub = end;
                }
            }
            end++;
        }
 
        for (int i = start_sub; i <= end_sub; i++) {
            Console.Write(str[i]);
        }
    }
     
    public static void Main(string[] args)
    {
        string str = "xwwwqfwwxqwyq";
 
        findLongestSubstringWithoutRepeatingCharacters(str);
    }
}
 
 
 
 
 
/*
run:
   
xqwy
   
*/

 



answered Jul 18, 2023 by avibootz
edited Jul 18, 2023 by avibootz
...