字符串分割为回文串(palindrome-partitioning-ii)

版权声明:本文为自学而写,如有错误还望指出,谢谢^-^ https://blog.csdn.net/weixin_43871369/article/details/89704933

题目描述

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

Solution 1(DFS方法搜索所有结果)

//动态规划方法
class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector<vector<string> >res;
        if(s.size()<=0) return res;
        vector<string>temp;
        int len=s.size();
        for(int i=1;i<=len;++i)
        {
            string word=s.substr(0,i);//先看str[0-i)是不是回文串
            if(!judge(word)) continue;//如果不是返回i+1
            temp.push_back(word);//如果是,递归调用返回后半字符串的所有可能回文串
            vector<vector<string> >part=partition(s.substr(i));
            Combine(res,temp,part);//合并结果
            temp.clear();//清除容器
        }
        return res;
    }
private:
    bool judge(string str)//判断是否为回文串
    {
        if(str.size()<=0) return false;
        if(str.size()==1) return true;
        else{
            int front=0;
            int later=str.size()-1;
            while(later>front)
            {
                if(str[front]!=str[later])
                    return false;
                --later;
                ++front;
            }
            return true;
        }
    }
void Combine(vector<vector<string> >&res,vector<string>temp,vector<vector<string> >part)
{
    if(part.size()<=0) res.push_back(temp);
    vector<string>storage;
    for(int i=0;i<part.size();++i)
    {
        storage=temp;
        for(int j=0;j<part[i].size();++j)
            storage.push_back(part[i][j]);
        res.push_back(storage);
    }
    return ;
}
};

猜你喜欢

转载自blog.csdn.net/weixin_43871369/article/details/89704933