Ejemplo n.º 1
0
        private void search(PalindromePairsTrie root, String[] words, int i, IList <IList <int> > result)
        {
            int len = words[i].Length;

            for (int j = 0; j < len && root != null; j++)
            {
                if (root.pos >= 0 && i != root.pos && IsPalindrome(words[i], j, len - 1))
                {
                    result.Add(new List <int> ()
                    {
                        i, root.pos
                    });
                }

                char ch = words[i][j];
                root = root.nodes[ch - 'a'];
            }

            if (root != null && root.palins.Count > 0)
            {
                foreach (var j in root.palins)
                {
                    if (j != i)
                    {
                        result.Add(new List <int> ()
                        {
                            i, j
                        });
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public IList <IList <int> > PalindromePairs_b(string[] words)
        {
            IList <IList <int> > result = new List <IList <int> > ();
            PalindromePairsTrie  trie   = new PalindromePairsTrie();

            for (int i = 0; i < words.Length; i++)
            {
                add(trie, words[i], i);
            }

            for (int i = 0; i < words.Length; i++)
            {
                search(trie, words, i, result);
            }

            return(result);
        }
Ejemplo n.º 3
0
        private void add(PalindromePairsTrie root, String word, int pos)
        {
            for (int i = word.Length - 1; i >= 0; i--)
            {
                char ch = word[i];

                if (IsPalindrome(word, 0, i))
                {
                    root.palins.Add(pos);
                }

                if (root.nodes[ch - 'a'] == null)
                {
                    root.nodes[ch - 'a'] = new PalindromePairsTrie();
                }

                root = root.nodes[ch - 'a'];
            }

            root.pos = pos;
            root.palins.Add(pos);
        }