【LeetCode】131. Palindrome Partitioning

本文介绍了一种通过空间换时间的方法解决回文串分割问题。使用二维数组记录字符串中所有子串是否为回文串,并采用深度优先搜索进行递归分割。

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"]
  ]

 

空间换时间。

使用二维数组isPalin记录每个子串是否为回文串。

然后递归来做。可以看做深度优先搜索。

class Solution {
public:
    vector<vector<bool> > isPalin;  // isPalin[i][j]==true means s[i,...,j] is palindrome
    void buildMap(string s)
    {
        int n = s.size();
        isPalin.resize(n, vector<bool>(n, false));
        for(int i = 0; i < n; i ++)
            isPalin[i][i] = true;
        for(int i = n-1; i >= 0; i --)
        {
            for(int j = i+1; j < n; j ++)
            {
                if(s[i] == s[j])
                {
                    if(j == i+1 || isPalin[i+1][j-1] == true)
                        isPalin[i][j] = true;
                }
            }
        }
    }
    vector<vector<string>> partition(string s) {
        buildMap(s);
        vector<vector<string> > ret;
        vector<string> cur;
        Helper(ret, cur, s, 0);
        return ret;
    }
    void Helper(vector<vector<string> >& ret, vector<string> cur, string s, int offset)
    {
        if(s == "")
            ret.push_back(cur);
        for(int i = 0; i < s.size(); i ++)
        {
            if(isPalin[offset+0][offset+i] == true)
            {
                cur.push_back(s.substr(0, i+1));    //palin prefix
                Helper(ret, cur, s.substr(i+1), offset+i+1);
                cur.pop_back();
            }
        }
    }
};

转载于:https://www.cnblogs.com/ganganloveu/p/4121762.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值