Next word that does not contain a palindrome and has characters from first k | Java 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
public class GFG { static void findNextWord ( char [ ] 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 ) { System . out . println ( " - 1" ) ; } else { System . out . println ( s ) ; } } public static void main ( String [ ] args ) { char [ ] str = " abcd " . toCharArray ( ) ; int k = 4 ; findNextWord ( str , k ) ; } }