131. Palindrome Partitioning

题目

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;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值