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

这又是一道需要用DFS来解的题目,既然题目要求找到所有可能拆分成回文数的情况,那么肯定是所有的情况都要遍历到,对于每一个子字符串都要分别判断一次是不是回文数,那么肯定有一个判断回文数的子函数,还需要一个DFS函数用来递归,再加上原本的这个函数,总共需要三个函数来求解。代码如下:

class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector<vector<string>> res;
        vector<string> out;
        partitionDFS(s, 0, out, res);
        return res;
    }
    void partitionDFS(string s, int start, vector<string> &out, vector<vector<string>> &res) {
        if (start == s.size()) {
            res.push_back(out);
            return;
        }
        for (int i = start; i < s.size(); ++i) {
            if (isPalindrome(s, start, i)) {
                out.push_back(s.substr(start, i - start + 1));
                partitionDFS(s, i + 1, out, res);
                out.pop_back();
            }
        }
    }
    bool isPalindrome(string s, int start, int end) {
        while (start < end) {
            if (s[start] != s[end]) return false;
            ++start;
            --end;
        }
        return true;
    }
};

本文转自博客园Grandyang的博客,原文链接:拆分回文串[LeetCode] Palindrome Partitioning ,如需转载请自行联系原博主。

相关文章
|
1月前
|
人工智能 BI
力扣561 数组拆分
力扣561 数组拆分
|
1月前
|
存储 canal 算法
[Java·算法·简单] LeetCode 125. 验证回文串 详细解读
[Java·算法·简单] LeetCode 125. 验证回文串 详细解读
23 0
|
3月前
|
Go
golang力扣leetcode 132.分割回文串II
golang力扣leetcode 132.分割回文串II
26 0
|
6月前
【Leetcode -680.验证回文串Ⅱ -693.交替位二进制数】
【Leetcode -680.验证回文串Ⅱ -693.交替位二进制数】
23 0
|
6月前
|
canal 算法
【Leetcode-121.买卖股票的最佳时机 -125.验证回文串】
【Leetcode-121.买卖股票的最佳时机 -125.验证回文串】
30 0
|
6月前
|
人工智能 BI
【Leetcode -561.数组拆分 -566.重塑矩阵】
【Leetcode -561.数组拆分 -566.重塑矩阵】
27 2
|
3月前
|
算法 测试技术
代码随想录 Day39 动态规划 LeetCode T139 单词拆分 动规总结篇1
代码随想录 Day39 动态规划 LeetCode T139 单词拆分 动规总结篇1
34 0
|
3月前
|
Go
golang力扣leetcode 139.单词拆分
golang力扣leetcode 139.单词拆分
17 0
|
3月前
|
存储 算法 C++
leetcode131分割回文串刷题打卡
leetcode131分割回文串刷题打卡
19 0
|
3月前
|
Java
leetcode-131:分割回文串
leetcode-131:分割回文串
20 1

热门文章

最新文章