您的位置:首页 > 其它

[LeetCode] Shortest Palindrome I

2015-08-03 11:13 253 查看
相关问题1:最长回文子串

相关问题2:Minimum
insertions to form a 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"
.
思路1:
首先判断给出的S是不是回文,然后判断在S左边添加 1 个字符后是不是回文,然后判断在S左边添加 2 个字符后是不是回文,然后判断在S左边添加 3 个字符后是不是回文。。。在S左边添加的字符要和S末尾的字符相对应。代码如下,测试的时候会超时。

class Solution {
public:
string shortestPalindrome(string s) {

int i = s.size()-1;
string pref = "";

while(!isPalin(pref+s))
{
pref = pref+s[i];
i--;
}

return pref+s;
}

bool isPalin(string str)
{
int i=0, j=str.size()-1;
while(i<j)
{
if(str[i]!=str[j])
return false;
else
{
i++;
j--;
}
}

return true;

}
};


思路2:

We can construct the following string and run KMP algorithm on it: (s) + (some symbol not present in s) + (reversed string)

After running KMP on that string as result we get a vector p with values of a prefix function for each character (for definition of a prefix function see KMP algorithm description). We are only interested in the last value
because it shows us the largest suffix of the reversed string that matches the prefix of the original string. So basically all we left to do is to add the first k characters of the reversed string to the original string, where k is a difference between original
string size and the prefix function for the last character of a constructed string.
class Solution {
public:
string shortestPalindrome(string s) {
string rev_s = s;
reverse(rev_s.begin(), rev_s.end());
string l = s + "#" + rev_s;

vector<int> p(l.size(), 0);
for (int i = 1; i < l.size(); i++) {
int j = p[i - 1];
while (j > 0 && l[i] != l[j])
j = p[j - 1];
p[i] = (j += l[i] == l[j]);
}

return rev_s.substr(0, s.size() - p[l.size() - 1]) + s;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: