就是一个字符串如“banana":最大重复字串就是"ana",出现了至少2次且最长。如果最长字符串有多个,那么方法一取的是第一次遇到的,方法二取得是多首字母开头最小的。如果没有重复的,那么返回thers is no repeat string!
- public class findMaxSubstring
- {
- class Program
- {
- static void Main(string[] args)
- {
- string s1;
- s1 = "明知道天要下雨就该带把伞,明知道不会有结果就请别开始!";
- Method1(s1);
- Method2(s1);
- }
- private static void Method2(string s1)
- {
- string[] strings = new string[s1.Length];
- //生成后缀数组
- for (int i = 0; i < s1.Length; i++)
- {
- strings[i] = s1.Substring(i);
- }
- //后缀数组排序
- for (int i = 0; i < s1.Length - 1; i++)
- {
- for (int j = 0; j < s1.Length - 1; j++)
- {
- if (strings[j].CompareTo(strings[j + 1]) == 1)
- {
- string s;
- s = strings[j];
- strings[j] = strings[j + 1];
- strings[j + 1] = s;
- }
- }
- }
- //求最大重复字串
- int max = 0, index = 0, a, b, n;
- for (int i = 0; i < s1.Length - 1; i++)
- {
- n = 0;
- while (n < strings[i].Length && n < strings[i + 1].Length && strings[i].Substring(0, n+1).Equals(strings[i + 1].Substring(0, n+1)))
- {
- n++;
- if (n > max)
- {
- max = n;
- index = i;
- }
- }
- }
- if (max == 0)
- {
- Console.WriteLine("方法2:maxlenth={0}", max);
- Console.WriteLine("there is no repeat string!");
- }
- else
- {
- Console.WriteLine("方法2:maxlenth={0}", max);
- Console.WriteLine(strings[index].Substring(0, max));
- }
- }
- private static void Method1(string s1)
- {
- int max = 0, index = 0, a, b, n;
- for (int i = 0; i < s1.Length; i++)
- for (int j = i + 1; j < s1.Length; j++)
- {
- n = 0;
- a = i; b = j;
- while (b < s1.Length && s1.Substring(a, 1).Equals(s1.Substring(b, 1)))
- {
- n++;
- a++;
- b++;
- }
- if (n > max)
- {
- max = n;
- index = j;
- }
- }
- if (max == 0)
- {
- Console.WriteLine("方法1:maxlenth={0}", max);
- Console.WriteLine("there is no repeat string!");
- }
- else
- {
- Console.WriteLine("方法1:maxlenth={0}", max);
- Console.WriteLine(s1.Substring(index, max));
- }
- }
- }