Ejemplo n.º 1
0
            public bool IsAnagram(NewPresentation np)
            {
                for (int i = 0; i < _charOccurences.Length; i++)
                {
                    if (_charOccurences[i] != np._charOccurences[i])
                    {
                        return(false);
                    }
                }

                return(true);
            }
Ejemplo n.º 2
0
        public IList <IList <string> > GroupAnagrams(string[] strs)
        {
            var result = new List <IList <string> >();

            if (strs.Length <= 0)
            {
                return(result);
            }

            var newPresentations = new NewPresentation[strs.Length];

            for (int i = 0; i < strs.Length; i++)
            {
                newPresentations[i] = new NewPresentation(strs[i], i);
            }

            var processed            = new bool[strs.Length];
            var groupedPresentations = newPresentations.GroupBy(np => np.GetHashCode());

            foreach (var group in groupedPresentations)
            {
                var groupContent = group.ToArray();
                if (groupContent.Length == 0)
                {
                    continue;
                }

                int countProcessed = 0;
                for (int i = 0; i < groupContent.Length && countProcessed < groupContent.Length; i++)
                {
                    if (processed[groupContent[i].IndexOriginalArray])
                    {
                        continue;
                    }

                    var newGroup = new List <string> {
                        groupContent[i].OriginalString
                    };
                    countProcessed++;
                    for (int j = i + 1; j < groupContent.Length; j++)
                    {
                        if (processed[groupContent[i].IndexOriginalArray])
                        {
                            continue;
                        }

                        if (groupContent[i].IsAnagram(groupContent[j]))
                        {
                            processed[groupContent[j].IndexOriginalArray] = true;
                            newGroup.Add(groupContent[j].OriginalString);
                            countProcessed++;
                        }
                    }
                    processed[groupContent[i].IndexOriginalArray] = true;
                    result.Add(newGroup);
                }
            }


            return(result);
        }