Sunday, November 13, 2016

#codingexercise

Get the length of the longest non-repeating character subsequence in a given input string

        static int GetLongestDistinctSubstringLength(String input)
        {
            var visited = new List<int>(256);
            visited.AddRange(Enumerable.Repeat(-1, 256));
            if (input.Length == 0) return 0;
            visited[input[0]] = 0;
            int prev = 0;
            int curLen = 1;
            int max = curLen;
            for (int i = 1; i < input.Length; i++)
            {
                prev = visited[input[i]];
                if (prev == -1 || i - curLen > prev)
                {
                    curLen++;
                }
                else
                {
                    if (curLen > max)
                    {
                        max = curLen;
                        Console.WriteLine(
                        "One non-repeating character substring found at index {0} is {1}",
                        i-max,
                        input.Substring(i-max, max));
                    }
                    curLen = i - prev;
                }
                visited[input[i]] = i;
            }
            if (curLen >= max)
            {
                max = curLen;
                Console.WriteLine(
                "One non-repeating character substring found at index {0} is {1}",
                input.Length - max,
                input.Substring(input.Length - max, max));
            }
            return max;
        }

            Console.WriteLine("Max = {0}", GetLongestDistinctSubstringLength("ABRACADABRA"));
            Console.WriteLine("Max = {0}", GetLongestDistinctSubstringLength("A"));
            Console.WriteLine("Max = {0}", GetLongestDistinctSubstringLength("AB"));
            Console.WriteLine("Max = {0}", GetLongestDistinctSubstringLength("AA"));
            Console.WriteLine("Max = {0}", GetLongestDistinctSubstringLength("ABC"));
            Console.WriteLine("Max = {0}", GetLongestDistinctSubstringLength("ABCA")); // expected ABC
            Console.WriteLine("Max = {0}", GetLongestDistinctSubstringLength("ABCB")); // expected ABC


One Non repeating character substring found at index 0 is ABR
One Non repeating character substring found at index 1 is BRAC
Max = 4
One Non repeating character substring found at index 0 is A
Max = 1
One Non repeating character substring found at index 0 is AB
Max = 2
One Non repeating character substring found at index 1 is A
Max = 1
One Non repeating character substring found at index 0 is ABC
Max = 3
One Non repeating character substring found at index 0 is ABC
One Non repeating character substring found at index 1 is BCA
Max = 3
One Non repeating character substring found at index 0 is ABC
Max = 3


We can make this recursive as well because the current character either participates in the max length or it doesn't.

No comments:

Post a Comment