文字列の最長重複しないサブストリングを見つけ、最大のサブストリングを出力します.
2750 ワード
例えばababcdebcでは、彼の最大のサブ文字列はabcdeです.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string s = "abcababcdefgfg";
char[] list = s.ToCharArray();
FindMaxSubDifferenceString ss = new FindMaxSubDifferenceString();
ss.FindMaxSubDifferenceStringS(list, s.Length);
string s1 = "aaaaaa";
char[] list1 = s1.ToCharArray();
ss.FindMaxSubDifferenceStringS(list1, s1.Length);
string s2 = "ababab";
char[] list2 = s2.ToCharArray();
ss.FindMaxSubDifferenceStringS(list2, s2.Length);
string s3 = "abcababcdefgfgabcababcdefgfg";
char[] list3 = s3.ToCharArray();
ss.FindMaxSubDifferenceStringS(list3, s3.Length);
}
}
public class FindMaxSubDifferenceString
{
public bool IsDup(char[] list, int len, char targetChar, int begin, int end, out int targetIndex)
{
targetIndex = -1;
// Note: first, we need to check all parameters are valid, such as list is null, len >0, or begin <end, begin>0, end<len, etc
for(int i=begin;i<=end; i++)
{
if(list[i]==targetChar)
{
targetIndex = i;
return true;
}
}
return false;
}
public void FindMaxSubDifferenceStringS(char[] list, int len)
{
if (list == null) return;
if (len <= 0) return;
int maxSubStringLen = 0;
int maxSubStringBeginIndex = 0;
int currentMaxSubStringBeginIndex = 0;
int currentMaxSubLen = 0;
for (int i = 1; i < len; i++)
{
int dupIndex = -1;
if (IsDup(list, len, list[i], currentMaxSubStringBeginIndex, i - 1, out dupIndex))
{
currentMaxSubLen = i - currentMaxSubStringBeginIndex;
if (currentMaxSubLen > maxSubStringLen)
{
maxSubStringLen = currentMaxSubLen;
maxSubStringBeginIndex = currentMaxSubStringBeginIndex;
}
else
{
}
currentMaxSubStringBeginIndex = dupIndex + 1;
}
else //not dup
{
}
}
if (maxSubStringLen == 0)
{
maxSubStringLen = len;
}
Console.Write("Input string: ");
for (int i = 0; i < len; i++)
{
Console.Write(list[i]);
}
Console.WriteLine("");
Console.Write("After Input: ");
for (int i = maxSubStringBeginIndex; i < maxSubStringBeginIndex + maxSubStringLen; i++)
{
Console.Write(list[i]);
}
Console.WriteLine("");
}
}
}