fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. int findpali(string s, int dp[][100], int st, int e);
  7. int main(void)
  8. {
  9. string s = "ABCD";
  10. int dp[100][100];
  11. for (int i = 0; i < 100; i++)
  12. for (int j = 0; j < 100; j++)
  13. dp[i][j] = -1;
  14. int out = findpali(s, dp, 0, s.length() - 1);
  15. cout << out << "\n";
  16. return 0;
  17. }
  18.  
  19.  
  20.  
  21. int findpali(string s, int dp[][100], int st, int e) // st ->starting position, e -> ending position
  22. {
  23. size_t length = s.length();
  24. if (st < 0 || st >= length || e < 0 || e >= length)
  25. cout << "This is trouble!!" << " st = " << st << " e = " << e << " but s has length " << length << "\n";
  26. if (s.length() == 1)
  27. {
  28. dp[st][e] = 1;
  29. return 1;
  30. }
  31. else if (s.length() == 2 && s[st] == s[e])
  32. {
  33. dp[st][e] = 2;
  34. return 2;
  35. }
  36. else if (dp[st][e] != -1)
  37. return dp[st][e];
  38. else if (s[st] == s[e])
  39. {
  40. dp[st][e] = findpali(s.substr(st + 1, s.length() - 2), dp, st + 1, e - 1) + 2;
  41. return dp[st][e];
  42. }
  43. else
  44. {
  45. dp[st][e] = max(findpali(s.substr(st, s.length() - 1), dp, st, e - 1), findpali(s.substr(st + 1, s.length() - 1), dp, st + 1, e));
  46. return dp[st][e];
  47. }
  48. }
Runtime error #stdin #stdout #stderr 0s 3464KB
stdin
Standard input is empty
stdout
This is trouble!!  st = 1  e = 3  but s has length 3
This is trouble!!  st = 2  e = 3  but s has length 1
This is trouble!!  st = 1  e = 2  but s has length 2
This is trouble!!  st = 2  e = 2  but s has length 0
stderr
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr: __pos (which is 3) > this->size() (which is 0)