LeetCode题解–131. Palindrome Partitioning

来源:互联网 发布:文字翻译语音软件 编辑:程序博客网 时间:2024/05/19 16:48

链接

LeetCode题目:https://leetcode.com/problems/palindrome-partitioning/

难度:Medium

题目

Given a string s, partition s such that every substring of the partition is a palindrome.

题目大意是给定一个字符串,返回所有子串是回文串的划分情况。比如s=”aab”,返回[ [“aa”,”b”], [“a”,”a”,”b”]]。

分析

使用dfs算法搜索划分点,当出现目前子串不是回文串时可以停止继续向下搜索。

代码

class Solution {public:    vector<vector<string>> partition(string s) {        if (s == "") ans.push_back({""});        else {            s_len = s.length();            ss = s;            vector<int> cut_point;            dfs(0, cut_point);        }        return ans;    }    bool isPalindrome(string str) {        int str_len = str.size();        for (int i = 0; i < str_len / 2; i++) {            if (str[i] != str[str_len - 1 - i]) return false;        }        return true;    }    void dfs(int n, vector<int> cut_point) {        int cut_len = (int) cut_point.size();        if (cut_len) {            int left_pos = cut_point[cut_len - 1];            string cut_str = ss.substr(left_pos, n - left_pos);            if (!isPalindrome(cut_str)) return;        }        cut_point.push_back(n);        if (n == s_len) {            vector<string> temp;            for (int i = 0; i < cut_point.size() - 1; i++) {                temp.push_back(ss.substr(cut_point[i], cut_point[i + 1] - cut_point[i]));            }            ans.push_back(temp);            return;        } else {            for (int i = n + 1; i <= s_len; i++) {                dfs(i, cut_point);            }        }    }private:    vector<vector<string>> ans;    int s_len;    string ss;};
0 0
原创粉丝点击