Palindrome Index

  • + 0 comments

    Here is my C++ solution

    // helper function
    bool isPalindrome ( const string & str)
    {
        for (int i = 0; i < str.length() / 2; i++)
        { 
            if (str[i] != str[str.length() - i - 1])
                return false;
        }
        return true;
    } 
    
    int  palindromeIndex(string& s)
    {
      int backward = 0, forward = s.size() - 1;
    
      bool bPallindrome = true;
    
      while (backward < forward) 
      {
          if (s[backward] != s[forward]) 
          {
              bPallindrome = false;
              break;
          }
          backward++;
          forward--;
      }
      int result = -1;
    
      if (!bPallindrome)
      {
        result = isPalindrome(s.erase(forward, 1)) ? forward: backward;
      }
      return result;
    

    }