LeetCode-Shortest Palindrome-解题报告

来源:互联网 发布:诲女知之乎翻译 编辑:程序博客网 时间:2024/05/05 02:40

原题链接:https://leetcode.com/problems/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.

For example:

Given "aacecaaa", return "aaacecaaa".

Given "abcd", return "dcbabcd".


在字符串的前面增加最少的字母使它成为回文串,说先最直接的方法是从字符串开始往后找找到最大的回文串,当然这样肯定是会超时的,因为我最开始就是这样做的。


我们发现其中可能出现很多连续重复的字母,

比如   aaabaaaa, 像这种在前面添加一个a就成回文串了,如果是这样的aaabaa,这样在前面就不能只是添加一个a,就需要添加aab aaabaa

如果连续的字符出现在中间,abbbcbbba,这样的本身就是回文串无需添加,如果是这样的abbcbbba,这样的就需要添加abbbcbb abbcbbba。

因此 先将其中的重复情况统计出来,str表示压缩后的字符串,cnt[i] 表示str[i]上的字符的个数。


然后我们使用最开始的方法,从str开头开始找最长的回文串,str剩余的部分直接逆序添加到字符串首部。


我使用isPalindrome(string& s, int& e)的方法判断其是否是回文。e表是结束的位置,其实位置是0,从中间往两边判断(这里要区分长度是奇数还是偶数)。

while(left > 0 && right < len)

if(s[left] == s[right] && cnt[left] == cnt[right]){ --left; ++right; continue; }

return false;

if(s[left] == s[right] && cnt[left] < cnt[right])return true;//这里left=0,right = len-1;

return false


找到之后只需要在其头部剩余的字符逆序添加


class Solution {public:    deque<int>cnt;string shortestPalindrome(string s) {if (s.length() < 2)return s;string str = "";sum(s, str);for (int i = str.length() - 1; i > 0; --i){if (str[i] != str[0])continue;if (isPalindrome(str, i)){if (cnt[i] > cnt[0]){for (int k = 0; k < cnt[i] - cnt[0]; ++k)s = str[i] + s;}for (int j = i + 1; j < str.length(); ++j){for (int k = 0; k < cnt[j]; ++k)s = str[j] + s;}return s;}}int t = 0;while (str[0] == s[t])t++;str = s;for (; t < s.length(); ++t){str = s[t] + str;}return str;}void sum(string& s, string& str){int c = 1;str.push_back(s[0]);for (int i = 1; i < s.length(); ++i){if (s[i] == str[str.length() - 1])c++;else cnt.push_back(c),c = 1, str += s[i];}cnt.push_back(c);}bool isPalindrome(string& s, int& e){int len = e, left, right;if (len % 2 == 0)left = len / 2 - 1, right = left + 2;else left = len / 2, right = left + 1;while (left > 0 && right < len){if (s[left] == s[right] && cnt[left] == cnt[right]){ --left; ++right; continue; }return false;}if (s[left] == s[right] && cnt[left] <= cnt[right])return true;return false;}};


0 0
原创粉丝点击