LeetCode(131)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"]
  ]


分析如下:

aab可以先切第一刀,可以构成的所有的子串组合是,

左子串a+ 右子串ab,

左子串aa + 右子串b, 

左字串aab + 右子串"",

如果其中的左字串是palindrome,则对右子串重复进行上面的步骤,所以是一个递归。否则,没有必要继续进行检测。

不过进行上面的流程,直到最后切到剩下的字串为空为止,这时候已经切到了第一个字串的最边界了。

我的代码:

第一版本

//128ms
class Solution {
public:
    bool isPalindrome (string s) {
        int i = 0, j = s.length() - 1;
        while(i <= j && s[i] == s[j]) {
            i++;
            j--;
        }
        return (j < i);
    }

    void my_partition(string s, vector<vector<string> > &final_result, vector<string> &every_result ) {
        if (s.length() ==0)
            final_result.push_back(every_result);
        for (int i =1; i <= s.length();++i) {
            string left = s.substr(0,i);
            string right = s.substr(i);
            if (isPalindrome(left)) {
                every_result.push_back(left);
                my_partition(right, final_result, every_result);
                every_result.pop_back();
            }
        }
    }
    
    vector<vector<string>> partition(string s) {
        vector<vector<string> > final_result;
        vector<string> every_result;
        my_partition(s, final_result, every_result);
        return final_result;
    }
};

上面的字符串要生成字串,涉及到大量的字符串生成和销毁,比较费时间,所以参考网上的一个版本,换了一个做法,用下标起止代替每次的字串。

//48ms
class Solution {
public:
    bool isPalindrome (string &s, int i, int j) {
        while(i <= j && s[i] == s[j]) {
            i++;
            j--;
        }
        return (j < i);
    }

    void my_partition(string s, int start, vector<vector<string> > &final_result, vector<string> &every_result ) {
        if (start >= s.length())
            final_result.push_back(every_result);
        for (int i = start ; i < s.length();++i) {
            if (isPalindrome(s, start, i)) {
                every_result.push_back(s.substr(start, i - start + 1));
                my_partition(s, i + 1, final_result, every_result);
                every_result.pop_back();
            }
        }
    }
    
    vector<vector<string>> partition(string s) {
        vector<vector<string> > final_result;
        vector<string> every_result;
        my_partition(s, 0, final_result, every_result);
        return final_result;
    }
};



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值