Reverse individual words with O ( 1 ) extra space | Java implementation of the approach ; Function to resturn the string after reversing the individual words ; Pointer to the first character of the first word ; If the current word has ended ; Pointer to the last character of the current word ; Reverse the current word ; Pointer to the first character of the next word ; Driver code
class GFG { static String swap ( String str , int i , int j ) { StringBuilder sb = new StringBuilder ( str ) ; sb . setCharAt ( i , str . charAt ( j ) ) ; sb . setCharAt ( j , str . charAt ( i ) ) ; return sb . toString ( ) ; } static String reverseWords ( String str ) { int start = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == ' ▁ ' || i == str . length ( ) - 1 ) { int end ; if ( i == str . length ( ) - 1 ) end = i ; else end = i - 1 ; while ( start < end ) { str = swap ( str , start , end ) ; start ++ ; end -- ; } start = i + 1 ; } } return str ; } public static void main ( String args [ ] ) { String str = " Geeks ▁ for ▁ Geeks " ; System . out . println ( reverseWords ( str ) ) ; } }