例如,abcdefg,xdefkl,那么最大相同子字符串为def
View Code
static string LongCommonSubstring(string str1, string str2) { if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2)) { throw new Exception("input can't be empty."); } string result = ""; int[,] strArr = new int[str1.Length, str2.Length]; int max = 0; for (int i = 0; i < str1.Length; i++) { for (int j = 0; j < str2.Length; j++) { strArr[i, j] = 0; if (str1[i] == str2[j]) { if (i - 1 >= 0 && j - 1 >= 0) { strArr[i, j] = strArr[i - 1, j - 1] + 1; } else { strArr[i, j] = 1; } if (max<strArr[i,j]) { max = strArr[i,j]; result = str1.Substring(i-max+1, max); } } } } Print(strArr); return result; } static void Print(int[,] intArr) { for (int i = 0; i < intArr.GetLength(0); i++) { for (int j = 0; j < intArr.GetLength(1); j++) { Console.Write(intArr[i,j]+","); } Console.WriteLine(); } }