|
| 1 | +#include <iostream> |
| 2 | +#include <fstream> |
| 3 | +#include <algorithm> |
| 4 | + |
| 5 | +std::string m_preProcess(std::string s) |
| 6 | +{ |
| 7 | + int n = s.length(); |
| 8 | + if (n == 0) return "^$"; |
| 9 | + std::string ret = "^"; |
| 10 | + for (int i = 0; i < n; i++) |
| 11 | + ret += "#" + s.substr(i, 1); |
| 12 | + |
| 13 | + ret += "#$"; |
| 14 | + return ret; |
| 15 | +} |
| 16 | + |
| 17 | +std::string longestPalindrome(std::string s) |
| 18 | +{ |
| 19 | + std::string T = m_preProcess(s); |
| 20 | + int n = T.length(); |
| 21 | + int *P = new int[n]; |
| 22 | + int C = 0, R = 0; |
| 23 | + for (int i = 1; i < n - 1; i++) |
| 24 | + { |
| 25 | + int i_mirror = 2 * C - i; // equals to i' = C - (i-C) |
| 26 | + |
| 27 | + P[i] = (R > i) ? std::min(R-i, P[i_mirror]) : 0; |
| 28 | + |
| 29 | + // Attempt to expand palindrome centered at i |
| 30 | + while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) |
| 31 | + P[i]++; |
| 32 | + |
| 33 | + // If palindrome centered at i expand past R, |
| 34 | + // adjust center based on expanded palindrome. |
| 35 | + if (i + P[i] > R) |
| 36 | + { |
| 37 | + C = i; |
| 38 | + R = i + P[i]; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // Find the maximum element in P. |
| 43 | + int maxLen = 0; |
| 44 | + int centerIndex = 0; |
| 45 | + for (int i = 1; i < n - 1; i++) |
| 46 | + { |
| 47 | + if (P[i] > maxLen) |
| 48 | + { |
| 49 | + maxLen = P[i]; |
| 50 | + centerIndex = i; |
| 51 | + } |
| 52 | + } |
| 53 | + delete[] P; |
| 54 | + |
| 55 | + return s.substr((centerIndex - 1 - maxLen) / 2, maxLen); |
| 56 | +} |
| 57 | + |
| 58 | +int main(int argc, char* argv[]) |
| 59 | +{ |
| 60 | + std::ifstream file("gettysburg.txt"); |
| 61 | + std::string ori_str; |
| 62 | + std::string longest_parlin_str; |
| 63 | + std::string color_str; |
| 64 | + int find_pos = 0; |
| 65 | + |
| 66 | + file >> ori_str; |
| 67 | + longest_parlin_str = longestPalindrome(ori_str); |
| 68 | + find_pos = ori_str.find(longest_parlin_str); |
| 69 | + |
| 70 | + color_str = ori_str.substr(0, find_pos) + "\033[33m" + longest_parlin_str |
| 71 | + + "\033[0m" + ori_str.substr(find_pos + longest_parlin_str.size(), |
| 72 | + ori_str.size() - find_pos - longest_parlin_str.size()); |
| 73 | + |
| 74 | + std::cout << color_str << std::endl; |
| 75 | + |
| 76 | + return 0; |
| 77 | +} |
0 commit comments