zoukankan      html  css  js  c++  java
  • C# 求最大相同子字符串

    例如,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();
                }
            }
  • 相关阅读:
    P2009 跑步
    P3916 图的遍历
    P2865 [USACO06NOV]路障Roadblocks
    P2820 局域网
    P2176 [USACO14FEB]路障Roadblock
    讨伐!数论
    网络流入门——EK算法
    最被低估的特质
    我的天哪我有博客了!
    Area POJ
  • 原文地址:https://www.cnblogs.com/Ligeance/p/2843004.html
Copyright © 2011-2022 走看看