Skip to content

Instantly share code, notes, and snippets.

@garyshort
Created July 13, 2020 14:22
Show Gist options
  • Save garyshort/9e9a0a40b9857d2bc9969ef886583516 to your computer and use it in GitHub Desktop.
Save garyshort/9e9a0a40b9857d2bc9969ef886583516 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
namespace _4Phil
{
class Program
{
static void Main(string[] args)
{
// Tests
int maxLength = LengthOfLongestString(
new string[3] { "ezy", "jnx", "btp" });
Console.WriteLine(maxLength == 9);
maxLength = LengthOfLongestString(
new string[3] { "co", "dil", "ity" });
Console.WriteLine(maxLength == 5);
maxLength = LengthOfLongestString(
new string[3] { "banana", "racecar", "potato" });
Console.WriteLine(maxLength);
}
static private int LengthOfLongestString(string[] aStringArray)
{
// Combine the elements into a single string
string s = String.Join(String.Empty, aStringArray);
// Fail fast. We need a minimum of one char to create a string
// with no repeating chars.
if(String.Empty == s) return -1;
int stopIndex = s.Length-1;
int currentMaxLength = 0;
for(int startIndex = 0; startIndex <= stopIndex; startIndex++ ){
for(int take = 1; take <= s.Length-startIndex; take++) {
string current = s.Substring(startIndex, take);
if(current.Distinct().Count() != current.Length) break;
if(current.Length > currentMaxLength)
currentMaxLength = current.Length;
}
}
return currentMaxLength;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment