最长回文子串(马拉车算法)
这是过了的:
inline int expand(string s, int left, int right) { while (left >= 0 && right < s.size() && s[left] == s[right]) { --left; ++right; } return (right - left - 2) / 2; } static void solve() { string s = "bbbbbbbbskfaaaaaaaaa"; string tmp = "#"; for (char c : s) { tmp += c; tmp += "#"; } int n = tmp.size(); int right = 0, center = 0, start = 0, maxLen = 0; vector<int> p(n, 0); for (int i = 0; i < n; ++i) { if (right >= i) { int minArmLen = min(right - i, p[2 * center - i]); p[i] = expand(tmp, i - minArmLen, i + minArmLen); } else { p[i] = expand(tmp, i, i); } if (i + p[i] > right) { center = i; right = i + p[i]; } if (p[i] > maxLen) { maxLen = p[i]; start = (i - p[i]) / 2; } } cout << s.substr(start, maxLen) << endl; }
不知道为啥这个没过:
static void solve() { int p[100]; int mr = 0, mc = 0, rl = 0;//int maxRight = 0, maxCenter = 0, resLen = 0; int st = 0; string bstr, str; bstr = "bbbbbbbbskfaaaaaaaaa"; for (auto x:bstr) { str.push_back('#'); str.push_back(x); } str.push_back('#'); for (int i = 0; i < str.length(); ++i) { if (i < mr) { if (p[2 * mc - i] < mr - i) { p[i] = p[2 * mc - i]; } else { p[i] = mr - i; while (i - p[i] >= 0 && i + p[i] < str.length() && str[i - p[i]] == str[i + p[i]])p[i]++; } } else { p[i] = 1; while (i - p[i] >= 0 && i + p[i] < str.length() && str[i - p[i]] == str[i + p[i]])p[i]++; } if (i + p[i] > mr) { //更新 mr = i + p[i]; mc = i; } if (p[i]>rl) { //记录 st = (i - p[i]) / 2; rl = p[i]; } } cout << bstr.substr(st,rl) << endl; return; }

浙公网安备 33010602011771号