Advertisement
SajolLol

find all distinct palindrome sub-strings

Jan 16th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. // C++ program to find all distinct palindrome sub-strings
  2. // of a given string
  3. #include <iostream>
  4. #include <map>
  5. using namespace std;
  6.  
  7. // Function to print all distinct palindrome sub-strings of s
  8. void palindromeSubStrs(string s)
  9. {
  10. map<string, int> m;
  11. int n = s.size();
  12.  
  13. // table for storing results (2 rows for odd-
  14. // and even-length palindromes
  15. int R[2][n+1];
  16.  
  17. // Find all sub-string palindromes from the given input
  18. // string insert 'guards' to iterate easily over s
  19. s = "@" + s + "#";
  20.  
  21. for (int j = 0; j <= 1; j++)
  22. {
  23. int rp = 0; // length of 'palindrome radius'
  24. R[j][0] = 0;
  25.  
  26. int i = 1;
  27. while (i <= n)
  28. {
  29. // Attempt to expand palindrome centered at i
  30. while (s[i - rp - 1] == s[i + j + rp])
  31. rp++; // Incrementing the length of palindromic
  32. // radius as and when we find vaid palindrome
  33.  
  34. // Assigning the found palindromic length to odd/even
  35. // length array
  36. R[j][i] = rp;
  37. int k = 1;
  38. while ((R[j][i - k] != rp - k) && (k < rp))
  39. {
  40. R[j][i + k] = min(R[j][i - k],rp - k);
  41. k++;
  42. }
  43. rp = max(rp - k,0);
  44. i += k;
  45. }
  46. }
  47.  
  48. // remove 'guards'
  49. s = s.substr(1, n);
  50.  
  51. // Put all obtained palindromes in a hash map to
  52. // find only distinct palindromess
  53. m[string(1, s[0])]=1;
  54. for (int i = 1; i <= n; i++)
  55. {
  56. for (int j = 0; j <= 1; j++)
  57. for (int rp = R[j][i]; rp > 0; rp--)
  58. m[s.substr(i - rp - 1, 2 * rp + j)]=1;
  59. m[string(1, s[i])]=1;
  60. }
  61.  
  62. //printing all distinct palindromes from hash map
  63. cout << "Below are " << m.size()-1
  64. << " palindrome sub-strings";
  65. map<string, int>::iterator ii;
  66. for (ii = m.begin(); ii!=m.end(); ++ii)
  67. cout << (*ii).first << endl;
  68. }
  69.  
  70. // Driver program
  71. int main()
  72. {
  73. palindromeSubStrs("abaaa");
  74. return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement