Leetcode之Shortest Palindrome

题目:

Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

Example 1:

Input: "aacecaaa"
Output: "aaacecaaa"

Example 2:

Input: "abcd"
Output: "dcbabcd"

代码:

超时方法一:

从后往前判断,从第一个字符到目前的字符是不是回文串,不是的话,记录字符;是的话,加上记录的字符。

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

string  shortestPalindrome(string s) {
	int len = s.length();
	if (len <= 1)return s;
	string record = "";
	for (int i = len - 1; i>=0; i--) {
		if (ispalindrome(s.substr(0, i + 1))) {
			record.append(s);
			break;
		}
		else {
			record.push_back(s[i]);
		}
	}
	return record;
}
};

方法二——KMP方法:

class Solution {
public:
    vector<int> getNext(string p) {
	int len = p.length();
	vector<int> next(len, 0);
	next[0] = -1;
	int k = -1, j = 0;
	while (j < len - 1) {
		if (k == -1 || p[j] == p[k]) {
			k++;
			j++;
			next[j] = k;
		}
		else {
			k = next[k];
		}
	}
	return next;
}

string  shortestPalindrome(string s) {
	string r = s;
	reverse(r.begin(), r.end());
	string t = s + "#" + r;
	vector<int> next = getNext(t);
	return r.substr(0,s.size()-1-next.back())+s;
}
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值