Tuesday, September 15, 2020

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

Example:

Input: "abcbm"
Output:
[
  ["a","bcb","m"],
  ["a","b","c","b","m"]
]

Approach: Its kind of permutation problem but here we only go to next index if sub-string is palindrome.

        public IList<IList<string>> PalindromPartitions(string s)

        {

            List<IList<string>> result = new List<IList<string>>();

            if (s?.Length <= 0)

            {

                return result;

            }

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

            this.PalindromPartitionsInternal(s, result, currResult, 0);

            return result;

        }


        private void PalindromPartitionsInternal(string s, List<IList<string>> result, List<string> currResult, int startIndex)

        {

            if (startIndex == s.Length)

            {

                result.Add(currResult);

                return;

            }

            for (int i = startIndex; i < s.Length; ++i)

            {

                if (this.IsPalindrome(s, startIndex, i))

                {

                    currResult.Add(s.Substring(startIndex, i - startIndex + 1));

                    this.PalindromPartitionsInternal(s, result, currResult, i + 1);

                    currResult.RemoveAt(currResult.Count - 1);

                }

            }

        }

No comments:

Post a Comment