// 動態規劃法解決兩個字符串中尋找最長公共子串
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Chapter17_最長子串
{
class Program
{
static void Main()
{
string word1;
string word2;
Console.WriteLine("請輸入字符串1: " );
word1 = Console.ReadLine();
Console.WriteLine("請輸入字符串2: ");
word2 = Console.ReadLine();
string[] warray1 = new string[word1.Length];
string[] warray2 = new string[word2.Length];
string substr;
int[,] larray = new int[word1.Length, word2.Length];
LCSubstring(word1, word2, warray1, warray2, larray);
Console.WriteLine();
Console.WriteLine("兩個字符串中最長公共子串比較的動態數組:");
DispArray(larray);
substr = ShowString(larray, warray1);
Console.WriteLine();
// Console.WriteLine("請輸入字符串1和字符串2: " + word1 + " " + word2);
if (substr.Length > 0)
Console.WriteLine("兩個字符串中最長公共子串: " + substr);
else
Console.WriteLine("兩個字符串中沒有最長公共子串. ");
}
static void LCSubstring(string word1, string word2, string[] warr1, string[] warr2, int[,] arr)
{
int len1, len2;
len1 = word1.Length;
len2 = word2.Length;
for (int k = 0; k <= word1.Length - 1; k++)
{
warr1[k] = word1.Substring(k, 1);
warr2[k] = word2.Substring(k, 1);
}
for (int i = len1 - 1; i >= 0; i--)
{
for (int j = len2 - 1; j >= 0; j--)
if (warr1[i] == warr2[j])
arr[i, j] = 1 + arr[i + 1, j + 1];
else
arr[i, j] = 0;
}
}
static string ShowString(int[,] arr, string[] wordArr)
{
string substr = "";
for (int i = 0; i <= arr.GetUpperBound(0); i++)
for (int j = 0; j <= arr.GetUpperBound(1); j++)
if (arr[i, j] > 0)
substr += wordArr[j];
return substr;
}
static void DispArray(int[,] arr)
{
for (int row = 0; row <= arr.GetUpperBound(0); row++)
{
for (int col = 0; col <= arr.GetUpperBound(1); col++)
Console.Write(arr[row, col]);
Console.WriteLine();
}
}
}
}
實驗截圖: