Modify a sentence by reversing order of occurrences of all Palindrome Words | Java implementation of the above approach ; Function to check if a string S is a palindrome ; Function to print the modified string after reversing teh order of occurrences of all palindromic words in the sentence ; Stores the palindromic words ; Stores the words in the list ; Traversing the list ; If current word is a palindrome ; Update newlist ; Reverse the newlist ; Traverse the list ; If current word is a palindrome ; Update lis [ i ] ; Increment j ; Print the updated sentence ; Driver code
import java . util . * ; class GFG { static boolean palindrome ( String str ) { int st = 0 ; int ed = str . length ( ) - 1 ; while ( st < ed ) { if ( str . charAt ( st ) == str . charAt ( ed ) ) { st ++ ; ed -- ; } else return false ; } return true ; } static void printReverse ( String sentence ) { ArrayList < String > newlist = new ArrayList < String > ( ) ; ArrayList < String > lis = new ArrayList < String > ( ) ; String temp = " " ; for ( char x : sentence . toCharArray ( ) ) { if ( x == ' ▁ ' ) { lis . add ( temp ) ; temp = " " ; } else temp += x ; } lis . add ( temp ) ; for ( String x : lis ) { if ( palindrome ( x ) ) newlist . add ( x ) ; } Collections . reverse ( newlist ) ; int j = 0 ; for ( int i = 0 ; i < lis . size ( ) ; i ++ ) { if ( palindrome ( lis . get ( i ) ) ) { lis . set ( i , newlist . get ( j ) ) ; j = j + 1 ; } } for ( String x : lis ) System . out . print ( x + " ▁ " ) ; } public static void main ( String [ ] args ) { String sentence = " mom ▁ and ▁ dad ▁ went ▁ to ▁ eye ▁ hospital " ; printReverse ( sentence ) ; } }