zoukankan      html  css  js  c++  java
  • C#动态规划查找两个字符串最大子串

     //动态规划查找两个字符串最大子串
            public static string lcs(string word1, string word2)
            {
                int max = 0;
                int index = 0;
                int[,] nums = new int[word1.Length + 1,word2.Length+1];
                for (int i = 0; i <= word1.Length; i++)
                {
                    for (int j = 0; j <= word2.Length; j++)
                    {
                        nums[i,j] = 0;
                    }
                }
     
     
                for (int i = 0; i <= word1.Length; i++)
                {
                    for (int j = 0; j <= word2.Length; j++)
                    {
                        if (i == 0 || j == 0)
                        {
                            nums[i, j] = 0;
                        }
                        else
                        {
                            if (word1[i - 1] == word2[j - 1])
                            {
                                nums[i,j] = nums[i - 1, j - 1] + 1;
                            }
                            else
                            {
                                nums[i, j] = 0;
                            }
                        }
                        if (max < nums[i, j])
                        {
                            max = nums[i, j];
                            index = i;
                        }
                    }
                }
                
                string str = "";
                if (max == 0)
                {
                    return "";
                }
                else 
                {
                    for (int i = index-max; i <= max; i++)
                    {
                        str += word2[i];
                    }
                    return str;
                }
            }
    好好学习,天天向上。
  • 相关阅读:
    软工实践寒假作业(1/2)
    javaSprintBoot技术总结
    个人作业——软件工程实践总结&个人技术博客
    个人作业软件评测
    结对第二次作业——某次疫情统计可视化的实现
    结对第一次—疫情统计可视化(原型设计)
    软工实践寒假作业(2/2)
    《软件工程》_寒假作业1_职业生涯规划
    部署前端项目和后端项目到服务器
    软件工程实践总结&个人技术博客
  • 原文地址:https://www.cnblogs.com/Zhengxue/p/6141495.html
Copyright © 2011-2022 走看看