Reverse Words in a String | String Problem | LeetCode 151
4 years ago Lalit Bhagtani 0
Problem Statement
You have given a String (containing multiple words), reverse the string word by word.
Example
Input :- "the sky is blue" Output :- "blue is sky the"
Input :- " hello world! " Output :- "world! hello"
Input :- "sun rise in the morning" Output :- "morning the in rise sun"
Solution
This problem can be solved in following steps :-
- If the input string is null or empty, then return the same string as an output otherwise moves to the next step.
- Create an array of characters from the input string and an object of StringBuffer class for writing output.
- Traverse the character array from the end and find out the end and start index of a single word.
- Write the word found in the previous step followed by a single space.
- Repeat steps 3 and 4, until the array is completely traversed.
Program
public class Main { public static void main(String[] args) { Main main = new Main(); String result = main.reverseWords("sun rise in the morning"); System.out.print(result); } /* Solution */ public String reverseWords(String str) { if(str == null || str.length() == 0) return str; StringBuilder sb = new StringBuilder(); char[] array = str.toCharArray(); int end = -1, i; for(i=array.length-1; i>=0; i--){ if(array[i] == ' '){ if(end != -1){ write(array, i+1, end, sb); end = -1; } }else { if(end == -1) end = i; } } if(end != -1){ write(array, 0, end, sb); } return sb.length() > 0 ? sb.substring(0, sb.length()-1).toString() : ""; } public void write(char[] array, int start, int end, StringBuilder sb){ while(start<=end){ sb.append(String.valueOf(array[start++])); } sb.append(" "); } }
Result
morning the in rise sun
Similar Post
That’s all for Reverse Words in a String in Java, If you liked it, please share your thoughts in a comments section and share it with others too.