每日一题——分割两个字符串得到回文串

一开始的超时解答:

class Solution { public: bool checkPalindrome(string a) { int len = a.length(); int j = len - 1; for (int i = 0; i < j; i++) { if (a[i] != a[j]) { return false; } j--; } return true; } bool checkPalindromeFormation(string a, string b) { int len = a.length(); if (checkPalindrome(a) || checkPalindrome(b)) { return true; } string temp1 = ""; string temp2 = b; string temp3 = ""; string temp4 = a; for (int i = 0; i < len; i++) { temp1 += a[i]; temp2 = b; temp2 = temp2.erase(0, i+1); temp3 += b[i]; temp4 = a; temp4 = temp4.erase(0, i+1); if (checkPalindrome(temp1 + temp2) || checkPalindrome(temp3 + temp4)) { return true; } } return false; } };

然后发现超时之后进行更正判断,发现只需刨去字符串a与字符串b相同前后缀之后,判断剩余的字符串a/b是不是回文串即可。

class Solution {
public:
    bool checkPalindrome(string a) {
        int j = a.length() - 1;
        for (int i = 0; i < j; i++) {
            if (a[i] != a[j]) {
                return false;
            }
            j--;
        }
        return true;
    }

    string substr(string a, int i) {
        int len = a.length();
        a = a.erase(len - i, len);
        a = a.erase(0, i);
        return a;
    }

    bool checkPalindromeFormation(string a, string b) {
        int len = a.length();
        bool index1 = true;
        bool index2 = true;
        for (int i = 0; i < len; i++) {
            if (index1) {
                if (a[i] == b[len - 1 - i]) {
                    if (i >= len / 2) {
                        return true;
                    }
                }
                else {
                    if (checkPalindrome(substr(a, i)) || checkPalindrome(substr(b, i))) {
                        return true;
                    }
                    index1 = false;
                }
            }
            if (index2) {
                if (b[i] == a[len - 1 - i]) {
                    if (i >= len / 2) {
                        return true;
                    }
                }
                else {
                    if (checkPalindrome(substr(a, i)) || checkPalindrome(substr(b, i))) {
                        return true;
                    }
                    index2 = false;
                }
            }
        }
        return false;
    }
};

示例代码:

class Solution { public: bool f(string a,string b) { int l = 0, r = b.size() - 1; while (l <= r && a[l] == b[r]) ++l,--r; return ff(a,l,r) || ff(b,l,r); } bool ff(string a,int l,int r) { while (l <= r) { if (a[l] != a[r]) return false; ++l,--r; } return true; } bool checkPalindromeFormation(string a, string b) { return f(a,b) || f(b,a); } };

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值