Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace LongestSubstring
- {
- using System;
- internal class Program
- {
- // This function returns true if all characters in
- // str[i..j] are distinct, otherwise returns false
- public static bool AreDistinct(string str, int i, int j)
- {
- // Note : Default values in visited are false
- bool[] visited = new bool[26];
- for (int k = i; k <= j; k++)
- {
- if (visited[str[k] - 'a'] == true)
- {
- return false;
- }
- visited[str[k] - 'a'] = true;
- }
- return true;
- }
- // Returns length of the longest substring
- // with all distinct characters.
- public static int LongestUniqueSubsttr(string str)
- {
- int n = str.Length;
- // Result
- int res = 0;
- for (int i = 0; i < n; i++)
- {
- for (int j = i; j < n; j++)
- {
- if (AreDistinct(str, i, j))
- {
- res = Math.Max(res, j - i + 1);
- }
- else
- {
- // note: newly added to avoid going n time when there is a duplication in some n[i]
- i = j - 1; // it will be adjusted by the for loop
- break;
- }
- }
- }
- return res;
- }
- // Driver code
- public static void Main()
- {
- string str = "geeksforgeeks";
- Console.WriteLine("The input string is " + str);
- int len = LongestUniqueSubsttr(str);
- Console.WriteLine("The length of the longest " +
- "non-repeating character " +
- "substring is " + len);
- Console.ReadLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement