How to find the longest repeating substring in a string with C#

1 Answer

0 votes
using System;

public class Program
{
	public static string longestCommonPrefix(string sub1, string sub2) {
		int min = Math.Min(sub1.Length, sub2.Length);

		for (int i = 0; i < min; i++) {
			if (sub1[i] != sub2[i]) {
				return sub1.Substring(0, i);
			}
		}
		return sub1.Substring(0, min);
	}

	public static string longestRepeatingSubstring(string s) {
		string lrs = "";
		int size = s.Length;

		for (int i = 0; i < size; i++) {
			for (int j = i + 1; j < size; j++) {
				string lcp = longestCommonPrefix(s.Substring(i, size - i), s.Substring(j, size - j));
				if (lcp.Length > lrs.Length) {
					lrs = lcp;
				}
			}
		}

		return lrs;
	}

	public static void Main(string[] args)
	{
		string s = "pythonphpjavacdartcppjavacsharp";

		Console.WriteLine(longestRepeatingSubstring(s));
	}
}





/*
run:

pjavac

*/

 



answered Jan 17, 2023 by avibootz
...