Reverse words in a given String in Java
Let’s see an approach to reverse words of a given String in Java without using any of the String library function Examples:
Input : "Welcome to geeksforgeeks" Output : "geeksforgeeks to Welcome" Input : "I love Java Programming" Output :"Programming Java love I"
Prerequisite: Regular Expression in Java
geeksforgeeks to Welcome Programming Java love I
Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n)
Approach: Without using split() or trim()
By this approach, we can even remove extra trailing spaces and in between the words also.
Basically, this algorithm involves 3 steps.
- If you find white space, there can be two possibilities.
- It might be end of a word or else extra trailing space in between the words.
- if it is not a white space, add the character to temporary word as shown in the below code.
Below is the implementation of above approach.
Before reversing length of string : 34 After reversing length of string : 26 "Geeks For Geeks to Welcome" Before reversing length of string : 34 After reversing length of string : 23 "Programming Java Love I"
Time Complexity: O(N) N is length of string
Auxiliary Space: O(1)
You can find the c++ solution for Reverse words in a String here This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...