Next word that does not contain a palindrome and has characters from first k | CPP program to find lexicographically next word which contains first K letters of the English alphabet and does not contain a palindrome as it 's substring of length more than one. ; function to return lexicographically next word ; we made m as m + 97 that means our required string contains not more than m + 97 ( as per ASCII value ) in it . ; increment last alphabet to make next lexicographically next word . ; if i - th alphabet not in first k letters then make it as " a " and then increase ( i - 1 ) th letter ; to check whether formed string palindrome or not . ; increment i . ; if i less than or equals to one that means we not formed such word . ; Driver code for above function .
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNextWord ( string s , int m ) { m += 97 ; int n = s . length ( ) ; int i = s . length ( ) - 1 ; s [ i ] ++ ; while ( i >= 0 && i <= n - 1 ) { if ( s [ i ] >= m ) { s [ i ] = ' a ' ; s [ -- i ] ++ ; } else if ( s [ i ] == s [ i - 1 ] s [ i ] == s [ i - 2 ] ) s [ i ] ++ ; else i ++ ; } if ( i <= -1 ) cout << " - 1" ; else cout << s ; } int main ( ) { string str = " abcd " ; int k = 4 ; findNextWord ( str , k ) ; return 0 ; }