⬅ Previous Topic
Calculate Sum of Beauty of All Substrings - Optimal ApproachNext Topic ⮕
Set Matrix Zeroes⬅ Previous Topic
Calculate Sum of Beauty of All Substrings - Optimal ApproachNext Topic ⮕
Set Matrix ZeroesTopic Contents
Given a string containing one or more words separated by spaces, your task is to reverse each word individually, while keeping the order of words the same.
Each word is defined as a sequence of characters separated by spaces. Spaces should be preserved between words, but the characters of each word should appear in reverse order.
This operation should not affect extra spaces or punctuation. The final result should be a single string with all words reversed.
public class ReverseWords {
public static String reverseEachWord(String s) {
String[] words = s.split(" ", -1); // include trailing spaces
StringBuilder result = new StringBuilder();
for (int i = 0; i < words.length; i++) {
StringBuilder word = new StringBuilder(words[i]);
result.append(word.reverse());
if (i != words.length - 1) result.append(" ");
}
return result.toString();
}
public static void main(String[] args) {
String input = "Hello World";
System.out.println("Reversed: " + reverseEachWord(input));
}
}
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | We scan each character in the string once during splitting, reversing, and joining. |
Average Case | O(n) | Each word is reversed individually, and all characters are processed linearly. |
Average Case | O(n) | Even if the string has long words or many spaces, we still traverse each character only once. |
O(n)
Explanation: A new string is built to store the reversed output, proportional to the input size.
⬅ Previous Topic
Calculate Sum of Beauty of All Substrings - Optimal ApproachNext Topic ⮕
Set Matrix ZeroesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.