c# leetcode 面試題 10.02. 變位詞組 超時了

 編寫一種方法,對字符串數組進行排序,將所有變位詞組合在一起。變位詞是指字母相同,但排列不同的字符串。

注意:本題相對原題稍作修改

示例:

輸入: ["eat", "tea", "tan", "ate", "nat", "bat"],
輸出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

說明:

  • 所有輸入均爲小寫字母。
  • 不考慮答案輸出的順序。

將所有可能性存入hashset,會自動去掉重複,然後依次執行,思路很清晰,過程很明瞭,但是執行會超時。

        static void Main(string[] args)
        {
            string[] str = new string[] { "eat", "tea", "tan", "ate", "nat", "bat" };
            Console.Write(GroupAnagrams(str));
            Console.ReadKey();
        }
        public static IList<IList<string>> GroupAnagrams(string[] strs)
        {
            IList<IList<string>> res=new List<IList<string>>();
            HashSet<string> set = new HashSet<string>();
            for (int i = 0; i < strs.Length; i++)
            {
                char[] c= strs[i].ToCharArray();
                Array.Sort(c);
                string cs = new string(c);
                set.Add(cs); 
            }
            foreach (var item in set)
            {
                List<string> str = GetListstring(item, strs);
                res.Add(str);
            }
            return res;
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章