41std::string
manacher(
const std::string &prototype) {
42 if (prototype.size() > 0) {
45 std::string stuffed_string =
"";
46 for (
auto str : prototype) {
47 stuffed_string += str;
48 stuffed_string +=
"#";
50 stuffed_string =
"@#" + stuffed_string +
"&";
52 std::vector<uint64_t> palindrome_max_half_length(
53 stuffed_string.size(),
59 uint64_t bigger_center =
69 for (uint64_t i = 1; i < stuffed_string.size() - 1; i++) {
72 uint64_t opposite_to_i =
81 palindrome_max_half_length[i] = std::min(
82 palindrome_max_half_length[opposite_to_i], right - i);
87 while (stuffed_string[i + (palindrome_max_half_length[i] + 1)] ==
88 stuffed_string[i - (palindrome_max_half_length[i] + 1)]) {
89 palindrome_max_half_length[i]++;
96 if (i + palindrome_max_half_length[i] > right) {
98 right = i + palindrome_max_half_length[i];
103 uint64_t half_length = 0;
104 uint64_t center_index = 0;
106 for (uint64_t i = 1; i < stuffed_string.size() - 1; i++) {
107 if (palindrome_max_half_length[i] > half_length) {
108 half_length = palindrome_max_half_length[i];
113 std::string palindromic_substring =
116 if (half_length > 0) {
122 center_index - half_length +
125 center_index + half_length -
127 for (uint64_t index = start; index <= end; index += 2) {
128 palindromic_substring += stuffed_string[index];
134 palindromic_substring = prototype[0];
136 return palindromic_substring;
152 assert(strings::manacher::manacher(
"") ==
"");
153 assert(strings::manacher::manacher(
"abababc") ==
"ababa");
154 assert(strings::manacher::manacher(
"cbaabd") ==
"baab");
155 assert(strings::manacher::manacher(
"DedzefDeD") ==
"DeD");
156 assert(strings::manacher::manacher(
"XZYYXXYZXX") ==
"YXXY");
157 assert(strings::manacher::manacher(
"1sm222m10abc") ==
"m222m");
158 assert(strings::manacher::manacher(
"798989591") ==
"98989");
159 assert(strings::manacher::manacher(
"xacdedcax") ==
"xacdedcax");
160 assert(strings::manacher::manacher(
"xaccax") ==
"xaccax");
161 assert(strings::manacher::manacher(
"a") ==
"a");
162 assert(strings::manacher::manacher(
"xy") ==
"x");
163 assert(strings::manacher::manacher(
"abced") ==
"a");
165 std::cout <<
"All tests have passed!" << std::endl;