逆向最大匹配分词算法C#

逆向顺序

句子:大家好我叫XX我是一名程序员

程序员  ->  序员  ->  员

名程序  ->  程序  ->  序

一名程  ->  名程  ->  程

是一名  ->  一名  ->  名

我是一  ->  是一  ->  一

X我是   ->  我是  ->  是

XX我    ->  X我  ->  我

叫XX    ->  XX   ->  X

我叫X   ->  叫X  ->  X

好我叫  ->  我叫  ->  叫

家好我  ->  好我  ->  我

大家好  ->  家好  ->  好

大家     ->  家

复制代码
class Program
    {
        public static HashSet<string> dictionary = new HashSet<string>();

        static void Main(string[] args)
        {
            Initail();
            List<string> list = new List<string>();
            string s = "大家好我叫XX我是一名程序员";
            string[] sentences = s.Split(',');
            int max = 3;
            for (int i = 0; i < sentences.Length; i++)
            {
                string str = sentences[i];
                int start = sentences[i].Length - max;
                int len = sentences[i].Length - start;
                while (len > 0)
                {
                    string subWord = sentences[i].Substring((start < 0 ? 0 : start), len);
                    Console.WriteLine(subWord);
                    if (Search(subWord))
                    {
                        list.Add(subWord);
                        start = start - max;
                        if (start < 0)
                        {
                            len = start < 0 ? max + start : max;
                        }
                    }
                    else
                    {
                        int k = 1;
                        bool flag = false;
                        string tempWord = null;
                        for (; k <= subWord.Length - 1; k++)
                        {
                            tempWord = subWord.Substring(k);
                            Console.WriteLine(tempWord);
                            if (Search(tempWord))
                            {
                                flag = true;
                                list.Add(tempWord);
                                break;
                            }
                        }
                        if (flag)
                        {
                            start = start - tempWord.Length;
                        }
                        else
                        {
                            start--;
                        }
                        len = start < 0 ? max + start : max;
                    }
                }
            }
            foreach (string x in list)
            {
                Console.WriteLine(x);
            }
            Console.ReadKey();
        }

        public static void Initail()
        {
            dictionary.Add("大家");
            dictionary.Add("好");
            dictionary.Add("我");
            dictionary.Add("一名");
            dictionary.Add("程序员");
            dictionary.Add("nick");
        }

        public static bool Search(string word)
        {
            return dictionary.Contains(word);
        }
    }
复制代码
原文地址:https://www.cnblogs.com/soundcode/p/4931166.html