Remove a character from a string to make it a palindrome | C # program to check whether it is possible to make string palindrome by removing one character ; Utility method to check if substring from low to high is palindrome or not . ; This method returns - 1 if it is not possible to make string a palindrome . It returns - 2 if string is already a palindrome . Otherwise it returns index of character whose removal can make the whole string palindrome . ; Initialize low and right by both the ends of the string ; loop until low and high cross each other ; If both characters are equal then move both pointer towards end ; * If removing str [ low ] makes the * whole string palindrome . We basically * check if substring str [ low + 1. . high ] * is palindrome or not . ; * If removing str [ high ] makes the whole string * palindrome . We basically check if substring * str [ low + 1. . high ] is palindrome or not . ; We reach here when complete string will be palindrome if complete string is palindrome then return mid character ; Driver Code
using System ; class GFG { static bool isPalindrome ( string str , int low , int high ) { while ( low < high ) { if ( str [ low ] != str [ high ] ) return false ; low ++ ; high -- ; } return true ; } static int possiblePalinByRemovingOneChar ( string str ) { int low = 0 , high = str . Length - 1 ; while ( low < high ) { if ( str [ low ] == str [ high ] ) { low ++ ; high -- ; } else { if ( isPalindrome ( str , low + 1 , high ) ) return low ; if ( isPalindrome ( str , low , high - 1 ) ) return high ; return - 1 ; } } return - 2 ; } public static void Main ( String [ ] args ) { string str = " abecbea " ; int idx = possiblePalinByRemovingOneChar ( str ) ; if ( idx == - 1 ) Console . Write ( " Not ▁ Possible " ) ; else if ( idx == - 2 ) Console . Write ( " Possible ▁ without ▁ " + " removing ▁ any ▁ character " ) ; else Console . Write ( " Possible ▁ by ▁ removing " + " ▁ character ▁ at ▁ index ▁ " + idx ) ; } }