Challenge: Mirror Each Word
Completed
Read a line of words separated by single spaces. Reverse the letters of each word but keep the words in their places.
Input
One line of words.
Output
The same words, each one reversed, separated by single spaces.
Example
Input
hello world
Output
olleh dlrow
Editor
Java
Hints
Split the line into words.
new StringBuilder(word).reverse() flips one word.
Solution explanation
Each character is touched a couple of times: O(n) for a line of n characters.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] words = sc.nextLine().trim().split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
if (i > 0) sb.append(' ');
sb.append(new StringBuilder(words[i]).reverse());
}
System.out.println(sb);
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module