131. Palindrome Partitioning

来源:互联网 发布:淘宝一元捡漏 编辑:程序博客网 时间:2024/06/03 15:20

题目

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = “aab”,
Return

[ [“aa”,”b”], [“a”,”a”,”b”] ]

思路

利用 深度优先搜索去找一个字符串中的回文字符串
如果采用以下算法,找到的子字符串依次为:

[“a”,”a”,”b”]
[“aa”,”b”]

再看一个例子 s = “aacc”

[a, a, c, c]
[a, a, cc]
[aa, c, c]
[aa, cc]

实现代码

  public class Solution    {        public IList<IList<string>> Partition(string s)        {            IList<IList<string>> rtn = new List<IList<string>>();            subPartition(rtn, new List<string>(), s, 0);            return rtn;        }        void subPartition(IList<IList<string>> rslt, IList<string> curItem, string s, int start)        {                       if (start == s.Length)//搜索的起始位置如果到了终点,说明找到了一组解            {                rslt.Add(new List<string>(curItem));                return;            }            for (int i = start; i < s.Length; i++) //广度方向            {                string str = s.Substring(start, i -start + 1); //get substring from start index of s                 if (isPalindrome(str))                {                    curItem.Add(str);                    //深度方向递归                    subPartition(rslt, curItem, s, i + 1);                     curItem.RemoveAt(curItem.Count - 1);                }            }        }        bool isPalindrome(string s)        {            int lo = 0, hi = s.Length - 1;            while (lo < hi)            {                if (s[lo++] != s[hi--])                    return false;            }            return true;        }    }