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

N个字符串中的最大公子串

2012年10月21日 ⁄ 综合 ⁄ 共 1222字 ⁄ 字号 评论关闭
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MaxPublicSubStr
{
    class Program
    {
        static void Main(string[] args)
        {
            //slfjsafl;ispfw
            List<string> list = new List<string>();
            list.Add("abcdefabcdeslfjsafl;ispfw");
            list.Add("abeslfjsafl;ispfwfgabcdef");
            list.Add("werabcdefghslfjlasjflaskfjlfasjlfjslfjsafl;ispfweerslkjfposdamwel;erfsap");
            Console.Write(getMaxPublicSubStr(list));
            Console.ReadLine();
        }

        private static string getMinLengthStrInList(List<string> list)
        {
            string result = list[0];

            foreach (var item in list)
            {
                if (item.Length < result.Length)
                {
                    result = item;
                }
            }
            return result;
        }

        private static string getMaxLengthStrInList(List<string> list)
        {
            string result = list[0];

            foreach (var item in list)
            {
                if (item.Length > result.Length)
                {
                    result = item;
                }
            }
            return result;
        }

        private static bool isAllContain(List<string> list, string part)
        {
            bool result = true;
            foreach (var item in list)
            {
                if (!item.Contains(part))
                {
                    result = false;
                }
            }
            return result;
        }

        private static string getMaxPublicSubStr(List<string> list)
        {
            List<string> result = new List<string>();
            string basic = getMinLengthStrInList(list);
            for (var i = 0; i < basic.Length; i++)
            {
                for (var j = 1; j <= basic.Length - i; j++)
                {
                    if (isAllContain(list, basic.Substring(i, j)))
                    {
                        result.Add(basic.Substring(i, j));
                    }
                }
            }
            return getMaxLengthStrInList(result);
        }

    }
}

求N个字符串中的最大公子串。

抱歉!评论已关闭.