Here is my solution in (C#):
// ----------------------------------------------------------------------------
// Copyright (c) SimpleCoder 2013
// ----------------------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LongestSubstring
{
static class Program
{
// Find longest substring which contains just two unique characters.
static string LongestSubstring(string str)
{
int Len = str.Length;
// start index of current substring
int i = 0;
// end index of current substring
int j = 0;
// start index of the longest substring
int maxStart = 0;
// length of the longest substring
int maxLen = 0;
// Occurrence of each char in current substring
Dictionary<char, int> CountMap = new Dictionary<char, int>();
while (j < Len)
{
char ch = str[j];
if (!CountMap.ContainsKey(ch))
CountMap.Add(ch, 1);
else
++CountMap[ch];
// Increment i until there are at most
// 2 unique chars in current substring begin at i and end at j
while (CountMap.Count > 2 && i < j)
{
ch = str[i];
if (CountMap[ch] > 1)
--CountMap[ch];
else
CountMap.Remove(ch);
++i;
}
// If we got 2 chars in current substring and its length
// is the longest so far, update maxStart and maxLen
if (CountMap.Count == 2 && j - i >= maxLen)
{
maxStart = i;
maxLen = j - i + 1;
}
++j;
}
return str.Substring(maxStart, maxLen);
}
static void Main()
{
Assert.AreEqual("", LongestSubstring(""));
Assert.AreEqual("", LongestSubstring("a"));
Assert.AreEqual("ab", LongestSubstring("ab"));
Assert.AreEqual("cccccaaacccc", LongestSubstring("abaaabcccccaaaccccdd"));
}
}
}
Follow up, take a look at solution for a related but slightly different question:
Longest substring which begins and ends with two unique characters
No comments:
Post a Comment