现在的位置: 首页 > 综合 > 正文

LCS 两个字符串的最大公共子字符串

2013年10月28日 ⁄ 综合 ⁄ 共 1134字 ⁄ 字号 评论关闭

public static string LCS(string s1, string s2)
        {
            if (s1 == s2)
                return s1;
            else if (String.IsNullOrEmpty(s1) || String.IsNullOrEmpty(s2))
                return null;

            var d = new int[s1.Length, s2.Length];

            var index = 0;
            var length = 0;

            for (int i = 0; i < s1.Length; i++)
            {
                for (int j = 0; j < s2.Length; j++)
                {
                    // 左上角值
                    var n = i - 1 >= 0 && j - 1 >= 0 ? d[i - 1, j - 1] : 0;

                    // 当前节点值 = "1 + 左上角值" : "0"
                    d[i, j] = s1[i] == s2[j] ? 1 + n : 0;

                    // 如果是最大值,则记录该值和行号
                    if (d[i, j] > length)
                    {
                        length = d[i, j];
                        index = i;
                    }
                }
            }

            return s1.Substring(index - length + 1, length);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string s1 = "我抄我抄我抄抄抄:明月几时有,把酒问青天,不知天上宫阙,今夕是何年";
            string s2 = "苏轼曾经写过“明月几时有,把酒问青天”的千古名句";
            MessageBox.Show(s1.Length.ToString() + " " + s2.Length.ToString());

            string s = LCS(s1, s2);
            MessageBox.Show(s.ToString());
        }

【上篇】
【下篇】

抱歉!评论已关闭.