字符串数组到anagram字符串数组

时间:2014-08-30 18:17:08

标签: c# arrays string arraylist

   public static List<ArrayList> areAnagrams(string[] input)
    {
        List<ArrayList> anagramList = new List<ArrayList>();
        List<string> str = input.ToList();
        for (int i = 0; i < input.Length; i++)
        {
            input[i] = input[i].ToLower();
            input[i] = input[i].Replace(" ", "");
        }
        for (int i = 0; i < input.Length; i++)
        {
            ArrayList list = new ArrayList();
            list.Add(input[i]);

            char[] string1 = input[i].ToCharArray();
            Array.Sort(string1);               

            for (int j = i + 1; j < input.Length; j++)
            {
                char[] string2 = input[j].ToCharArray();
                Array.Sort(string2);

                if (string1.Length == string2.Length)
                {
                    bool isAnagram = true;

                    for (int k = 0; k < string1.Length; k++)
                    {
                        if (string1[k] != string2[k])
                        {
                            isAnagram = false;
                            break;
                        }
                    }

                    if (isAnagram)
                    {
                        list.Add(input[j]);
                        //input[i].Remove(i);
                    }
                }
            }

            anagramList.Add(list);
        }

        return anagramList;
    }

string[] str = new string[] { "pear", "dirty room", "amleth", "reap", "tinsel", "hamlet", "dormitory", "listen", "silent" }

结果应为:

[ {"pear","reap"}, {"dirty room","dormitory"}, {"amleth","hamlet"}, {"tinsel","listen","silent"} ]

问题是我无法删除已插入列表中的单词

2 个答案:

答案 0 :(得分:1)

我知道这不是你期望的答案,只是为了表现出不同的方式

string[] input = new string[] { "pear", "dirty room", "amleth", "reap", "tinsel", "hamlet", "dormitory", "listen", "silent" };

var anagramList = input
       .Select(s => new { org = s, sorted = String.Join("", s.Where(c => c != ' ').OrderBy(c => c)) })
       .GroupBy(x => x.sorted)
       .Select(g => g.Select(x => x.org).ToList())
       .ToList();

答案 1 :(得分:0)

而不是&#34;即时删除&#34;只需创建List<string> toRemove = new List<string>();

然后添加要删除的项目,完成后,只需创建简单的for-cycle:

foreach (string item in toRemove){
  input.delete(item);
}

(我大部分时间都在使用Java,所以也许这种语法不是100%正确,但它是关于&#34;怎么做&#34;)