1. 程式人生 > >leetcode刷題,manacher演算法

leetcode刷題,manacher演算法

下面是manacher演算法的實現程式碼:

class Solution {
public:
    string longestPalindrome(string s) {
  	string out;
	string str1 = init(s);
	//使用輔助資料記錄每個字元處的迴文串長度
	int* len = new int[str1.size()];
	for(int i = 0; i < str1.size(); i++)
        len[i] = 0;
	int mx = 0, p0 = 0;
	int maxLen = 0, pos = 0;
	for (int i = 1; i <= str1.size() - 2; i++)
	{
		if (i < mx) {
			len[i] = min(mx - i, len[2 * p0 - i]);
		}else{
			len[i] = 1; //如果i>mx,得重新匹配
		}
		while (str1[i + len[i]] == str1[i - len[i]])
		{
			len[i]++;
		}
		if (i + len[i] > mx) {
			p0 = i;
			mx = i + len[i];
		}
		pos = len[i] > maxLen ? i : pos;
		maxLen = len[i] > maxLen ? len[i] : maxLen;		
	}
	out = s.substr((pos - len[pos]) / 2, len[pos] - 1);
	return out;
    }
    
    string init(string str)
{
	string out(str.size() * 2 + 3, '*');//字串的開頭和結尾加上特殊字元,防止越界
	out[0] = '@';
	out[1] = '#';
	for (int i = 2; i <= out.size() - 3; i += 2)
	{
		out[i] = str[i / 2 - 1];
		out[i + 1] = '#';
	}
	out[out.size() - 1] = '$';
	return out;
}
};