马拉车算法(Manacher)

  1. pub fn manacher(s: String) -> String {
  2. let l = s.len();
  3. if l <= 1 {
  4. return s;
  5. }
  6. // MEMO: We need to detect odd palindrome as well,
  7. // therefore, inserting dummy string so that
  8. // we can find a pair with dummy center character.
  9. let mut chars: Vec<char> = Vec::with_capacity(s.len() * 2 + 1);
  10. for c in s.chars() {
  11. chars.push('#');
  12. chars.push(c);
  13. }
  14. chars.push('#');
  15. // List: storing the length of palindrome at each index of string
  16. let mut length_of_palindrome = vec![1usize; chars.len()];
  17. // Integer: Current checking palindrome's center index
  18. let mut current_center: usize = 0;
  19. // Integer: Right edge index existing the radius away from current center
  20. let mut right_from_current_center: usize = 0;
  21. for i in 0..chars.len() {
  22. // 1: Check if we are looking at right side of palindrome.
  23. if right_from_current_center > i && i > current_center {
  24. // 1-1: If so copy from the left side of palindrome.
  25. // If the value + index exceeds the right edge index, we should cut and check palindrome later #3.
  26. length_of_palindrome[i] = std::cmp::min(
  27. right_from_current_center - i,
  28. length_of_palindrome[2 * current_center - i],
  29. );
  30. // 1-2: Move the checking palindrome to new index if it exceeds the right edge.
  31. if length_of_palindrome[i] + i >= right_from_current_center {
  32. current_center = i;
  33. right_from_current_center = length_of_palindrome[i] + i;
  34. // 1-3: If radius exceeds the end of list, it means checking is over.
  35. // You will never get the larger value because the string will get only shorter.
  36. if right_from_current_center >= chars.len() - 1 {
  37. break;
  38. }
  39. } else {
  40. // 1-4: If the checking index doesn't exceeds the right edge,
  41. // it means the length is just as same as the left side.
  42. // You don't need to check anymore.
  43. continue;
  44. }
  45. }
  46. // Integer: Current radius from checking index
  47. // If it's copied from left side and more than 1,
  48. // it means it's ensured so you don't need to check inside radius.
  49. let mut radius: usize = (length_of_palindrome[i] - 1) / 2;
  50. radius += 1;
  51. // 2: Checking palindrome.
  52. // Need to care about overflow usize.
  53. while i >= radius && i + radius <= chars.len() - 1 && chars[i - radius] == chars[i + radius]
  54. {
  55. length_of_palindrome[i] += 2;
  56. radius += 1;
  57. }
  58. }
  59. // 3: Find the maximum length and generate answer.
  60. let center_of_max = length_of_palindrome
  61. .iter()
  62. .enumerate()
  63. .max_by_key(|(_, &value)| value)
  64. .map(|(idx, _)| idx)
  65. .unwrap();
  66. let radius_of_max = (length_of_palindrome[center_of_max] - 1) / 2;
  67. let answer = &chars[(center_of_max - radius_of_max)..(center_of_max + radius_of_max + 1)]
  68. .iter()
  69. .collect::<String>();
  70. answer.replace("#", "")
  71. }
  72. #[cfg(test)]
  73. mod tests {
  74. use super::manacher;
  75. #[test]
  76. fn get_longest_palindrome_by_manacher() {
  77. assert_eq!(manacher("babad".to_string()), "aba".to_string());
  78. assert_eq!(manacher("cbbd".to_string()), "bb".to_string());
  79. assert_eq!(manacher("a".to_string()), "a".to_string());
  80. let ac_ans = manacher("ac".to_string());
  81. assert!(ac_ans == "a".to_string() || ac_ans == "c".to_string());
  82. }
  83. }