LeetCode之“字符串”:最短回文子串

时间:2023-03-09 21:48:05
LeetCode之“字符串”:最短回文子串

  题目链接

  题目要求: 

  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".

  这道题用暴力破解是无法通过LeetCode上的测试的。

  1. 法一(暴力破解)

  超过时间!!!!

 int findCenter(string s)
{
int center = ;
int szS = s.size();
for (int i = ; i < szS; i++)
{
int k = ;
while (k <= i && k < szS - i)
{
if (s[i - k] != s[i + k])
break;
k++;
}
if (i - k == - && i > center)
center = i;
}
return center;
} string char2String(char c)
{
stringstream ss;
string s;
ss << c;
ss >> s;
return s;
} string shortestPalindrome(string s) {
// clear spaces
if (s.front() == ' ')
s.erase(, );
if (s.back() == ' ')
s.pop_back(); string ret;
int szS = s.size();
if (szS == )
ret = "";
else if (szS == )
{
s += s;
ret = s;
}
else
{
ret = s;
int center = findCenter(s);
int left = center;
int right = center + left + ;
if (szS - center - > center && s[center] == s[center + ])
{
right = szS;
}
for (int i = right; i < szS; i++)
{
ret.insert(, char2String(s[i]));
}
} return ret;
}

  2. 法二(暴力破解)

  法二思路来源:How to get the shortest palindrome of a string。重要语句摘录如下:

  Just append the reverse of initial substrings of the string, from shortest to longest, to the string until you have a palindrome. e.g., for "acbab", try appending "a" which yields "acbaba", which is not a palindrome, then try appending "ac" reversed, yielding "acbabca" which is a palindrome.

  法二相对法一来说更加简单容易理解,但同样超过时间!!!!

 bool isPalindrome(string  s)
{
int szS = s.size();
for (int i = ; i < szS / ; i++)
{
if (s[i] != s[szS - i - ])
return false;
}
return true;
} string shortestPalindrome(string s)
{
// clear spaces
if (s.front() == ' ')
s.erase(, );
if (s.back() == ' ')
s.pop_back();
//
string ret;
int szS = s.size();
if (szS == )
{
ret = "";
}
else if (szS == )
{
s += s;
ret = s;
}
else if (isPalindrome(s))
{
ret = s;
}
else
{
for (int i = ; i < szS; i++)
{
string tmpStr = s;
for (int j = szS - i - ; j < szS; j++)
tmpStr.insert(tmpStr.begin(), s[j]); if (isPalindrome(tmpStr))
{
ret = tmpStr;
break;
}
}
}
return ret;
}

  看来只能另寻他法了。。。。

  3. 法三

  法三参考自C++ 8 ms KMP-based O(n) time & O(n) memory solution,利用了KMP的思想。具体程序如下:

 class Solution {
public:
string shortestPalindrome(string s)
{
string rev_s(s);
reverse(rev_s.begin(), rev_s.end());
string combine = s + "#" + rev_s; // 防止在匹配的时候,不从‘#’后开始 int sz = combine.size();
vector<int> match(sz, );
int k = ;
for (int i = ; i < sz; i++) {
while (k > && combine[i] != combine[k])
k = match[k - ]; if (combine[i] == combine[k])
k = k + ; match[i] = k;
} return rev_s.substr(, s.size() - match[sz - ]) + s;
}
};

  上边程序可以解释如下:

  对构造的字符串combine进行匹配操作后,得到如下结果:

  LeetCode之“字符串”:最短回文子串

  匹配部分也就是s和rev_s重复的部分,而不匹配的部分就是它们不一样的部分。接下来的字符串拼接操作就是:

  LeetCode之“字符串”:最短回文子串

  拼接完成后即是最终的结果。