1. 程式人生 > >C#求單詞最長公共字首

C#求單詞最長公共字首

例如:class、classify、clean的公共最長字首為cl。
例如:count、key、open的最長公共字首為空字串。
程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>() { "class", "classify", "clean" };
            Console.WriteLine(GetCommonText(list));
            Console.ReadKey(true);
        }

        static string GetCommonText(List<string> list)
        {
            string text = string.Empty;
            if (list == null || list.Count < 2)
            {
                return text;
            }

            // 最短字串
            int length = list[0].Length;
            int index = 0;
            for (int i = 1; i < list.Count; i++)
            {
                if (list[i].Length <= length)
                {
                    length = list[i].Length;
                    index = i;
                }
            }

            // 求公共字首
            char[] charArray = list[index].ToArray();
            bool isEqual = true;
            for (int i = 0; i < charArray.Length; i++)
            {
                for (int j = 0; j < list.Count; j++)
                {
                    char[] tempArray = list[j].ToArray();
                    if (tempArray[i] != charArray[i])
                    {
                        isEqual = false;
                        break;
                    }
                }
                if (isEqual)
                {
                    text += charArray[i].ToString();
                }
                else
                {
                    break;
                }
            }
            return text;
        }
    }
}