Remove the first and last character and call the function for all characters
for ( char c1 = ' a ' ; c1 <= ' z ' ; c1 ++ ) if ( c1 != c ) { int len = s . Length - 2 ; char [ ] tmp = new char [ len ] ; Array . Copy ( s , 1 , tmp , 0 , len ) ; ans = Math . Max ( ans , 1 + solve ( tmp , c1 ) ) ; } }