fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. bool isPalindrome(string s)
  7. {
  8. if (s.length()<2) // empty strings and singles chars are no palindromes !
  9. return false;
  10. for (auto f=s.cbegin(), r=s.cend()-1; f!=r; r--) {
  11. if (*f!=*r) // if the nth letter from start doesn't match nth from ens
  12. return false; // not a palindrom
  13. if (++f==r) // if middle of string is between two chars
  14. break;
  15. }
  16. return true; // we meet in the middle so it's a palindrome
  17. }
  18.  
  19. int startWithPalindome(const string a)
  20. {
  21. if (a.length()>1)
  22. {
  23. for (int N = a.rfind(a[0]); N!=string::npos && N>0; N= a.rfind(a[0],N-1) ) {
  24. if ( isPalindrome(a.substr(0,N+1)) )
  25. return N+1;
  26. }
  27. }
  28.  
  29. return -1;
  30. }
  31.  
  32. int main() {
  33. string s1 = "ABBA";
  34. string s2 = "ABXBA";
  35. string s3 = "ABCA";
  36.  
  37. cout << "Testing isPalindrome():"<<endl;
  38. cout <<" "<< s1 << ": " << (isPalindrome(s1) ? "Ok":"fail") <<endl;
  39. cout <<" "<< s2 << ": " << (isPalindrome(s2) ? "Ok":"fail") <<endl;
  40. cout <<" "<< s3 << ": " << (isPalindrome(s3) ? "Fail":"Ok") <<endl;
  41. cout <<endl;
  42.  
  43. string b1=s1+"BLABL";
  44. string b2=s2+"BLABLA";
  45. string b3=s3+"BLABL";
  46.  
  47. cout << "Testing sart :"<<endl;
  48. cout <<" "<< b1 << ": " << startWithPalindome(b1)<<endl;
  49. cout <<" "<< b2 << ": " << startWithPalindome(b2)<<endl;
  50. cout <<" "<< b3 << ": " << startWithPalindome(b3)<<endl;
  51.  
  52. // your code goes here
  53. return 0;
  54. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Testing isPalindrome():
  ABBA: Ok
  ABXBA: Ok
  ABCA: Ok

Testing sart :
  ABBABLABL: 4
  ABXBABLABLA: 5
  ABCABLABL: -1