Reverse Each Word
Problem
Read one line where words are separated by single spaces. Reverse the letters of every word, but keep the order of the words.
Constraints
- 1 <= length <= 10^5, single spaces
Examples
Input
Hello World
Output
olleH dlroW
Solutions
Splitting gives the words. We reverse the letters inside each word and join the words again in the same order.
/*
* Problem : Reverse every word.
* Input : One line of text.
* Output : The line with reversed words.
* Approach: Reverse inside each word.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(String s) {
// Step 1: Split the line into words at single spaces.
String[] words = s.split(" ");
StringBuilder result = new StringBuilder();
// Step 2: Handle one word at a time.
for (int w = 0; w < words.length; w++) {
// Step 3: Add the letters of the word from the last to the first.
for (int i = words[w].length() - 1; i >= 0; i--) {
result.append(words[w].charAt(i));
}
// Step 4: Put a space between words.
if (w < words.length - 1) {
result.append(" ");
}
}
return result.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- Does the word order change?