給定一個單詞,從字典查找該單詞的所有兄弟單詞。


     最近在網上看到百度的一個面試題:一個單詞單詞字母交換,可得另一個單詞,如army->mary,成為兄弟單詞。提供一個單詞,在字典中找到它的兄弟。描述數據結構和查詢過程。

     我的思路是這樣的,所謂A單詞是B單詞的兄弟單詞,無非就是組成A和B兩個單詞的所有字母都是一樣,無非就是順序不一樣罷了。因此只要把單詞按照AscII值來進行排序,然后判斷下兩個拍好序的單詞是否完全一樣,如果完全一樣就是兄弟單詞,否則就不是。下面是我用C#實現的代碼。供參考,歡迎大家提供更好的思路。

      

       static void Main(string[] args)

        { 

            string[] Vocabularys = { "abcd", "ab", "army", "mary", "mnay", "mray", "myar", "rmay", "abcd" };

            Vocabularys = GetBrotherVocabularys(Vocabularys, "army");

            Console.WriteLine("the vocabularies of army's brother vocabulary are :");

            foreach (string vocabulary in Vocabularys)

            {

                Console.Write("{0} ", vocabulary);

            }

            Console.Read();

        }

        /// <summary>

        /// 把一個字符串單詞轉化為一個字符列表

        /// </summary>

        /// <param name="vocabulary"></param>

        /// <returns></returns>

        private static IList<char> GetCharListByVoca(string vocabulary)

        {

            return (from m in vocabulary.ToCharArray() orderby m ascending select m).ToList();

        }

 

        /// <summary>

        /// 給定一個字符串數組,返回該數組中的是給定字符串的兄弟字符串的那些字符串

        /// </summary>

        /// <param name="vocabularys">字符串數組</param>

        /// <param name="keyVocabulary">給定字符串</param>

        /// <returns></returns>

        private static string[] GetBrotherVocabularys(string[] vocabularys, string keyVocabulary)

        {

            List<string> lst = new List<string>();

            IList<char> keyList = GetCharListByVoca(keyVocabulary);

            int len = keyVocabulary.Length;

            foreach (string item in vocabularys)

            {

                if (item.Length == len)

                {

                    if (IsBrotherVoca(item, keyList))

                    {

                        lst.Add(item);

                    }

                }

            }

            return lst.ToArray();

        }

 

        private static bool IsBrotherVoca(string vocabulary, IList<char> keyVocaCharList)

        {

            IList<char> vocaCharList = GetCharListByVoca(vocabulary);        

            int i = 0;

            bool flag = true;

            foreach (char c in vocaCharList)

            {

                if (c != keyVocaCharList[i])

                {

                    flag = false;

                    break;

                }

                i++;

            }

            return flag;

        }

 

 

  運行結果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM