美文网首页
Leetcode131: 分割回文字符串

Leetcode131: 分割回文字符串

作者: VIELAMI | 来源:发表于2020-05-06 15:19 被阅读0次

【题目描述】
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回 s 所有可能的分割方案。


image.png

【思路】
使用回溯法
全局使用一个path
每次分割出一段字符,判断分割的的子字符串是否为回文,若为回文加入path,对剩下的继续进行。若不是回文则剪枝。
回溯结束的条件:字符串为空(全部已经分割)

vector<vector<string>> partition(string s) {
    //Leetcode131: 分割回文串
    vector<vector<string>> res;
    vector<string> path;
    if (s.size() == 0) return res;
    helpPar(s, res, path, 0);
    return res;

}
void helpPar(string s, vector<vector<string>>& res, vector<string>& path, int start) {
    //cout << "start: " << start << endl;
    //cout << "path: ";
    if (start >= s.size()) {
        res.push_back(path);
        return;
    }
    else {
        for (int i = start; i <s.size(); i++) {
            if (isPal(s, start, i)) {
                //cout << "pal start: " << start << endl;
                //cout << "pal end: " << i << endl;
                //cout << "isPal: " << s.substr(i, i - start + 1) << endl;;
                path.push_back(s.substr(start,i-start+1));
                helpPar(s, res, path, i+1);
                path.pop_back();
            }
        }
    }
}

bool isPal(string s, int start, int end) {
    if (start > end) return true;
    if (s[start] != s[end]) return false;
    if (s[start] == s[end]) return isPal(s, start + 1, end - 1);
}

相关文章

  • Leetcode131: 分割回文字符串

    【题目描述】给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 返回 s 所有可能的分割方案。 【...

  • leetcode131 分割回文串

    题目 分割回文串 分析 简单dfs问题,关键点在于如何快速的判断回文串。这里我们就可以预先找出所有的回文串,再每次...

  • leetcode131 分割回文串 golang

    131. 分割回文串[https://leetcode-cn.com/problems/palindrome-pa...

  • Leetcode. 回文字符串的分割和最少分割数

    Q1: 回文字符串的分割 Given a string s, partition s such that ever...

  • lintcode-分割回文串

    给定一个字符串s,将s分割成一些子串,使每个子串都是回文串。 返回s所有可能的回文串分割方案。

  • 131. 分割回文串

    给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。 回文串 ...

  • LeetCode 131. 分割回文串

    题目 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。回文...

  • LeetCode-131-分割回文串

    分割回文串 题目描述:给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能...

  • LeetCode 131 [Palindrome Partiti

    原题 给定一个字符串s,将s分割成一些子串,使每个子串都是回文串。返回s所有可能的回文串分割方案。 样例给出 s ...

  • 1616分割两个字符串得到回文串

    1616. 分割两个字符串得到回文串[https://leetcode-cn.com/problems/split...

网友评论

      本文标题:Leetcode131: 分割回文字符串

      本文链接:https://www.haomeiwen.com/subject/jldwghtx.html