878729. Print With Space
Basic
Print With Space
Summary
This problem involves printing a given string with spaces in between each character. The key concept involved is manipulating strings, specifically inserting characters at specific positions.
Detailed Explanation
The approach to solve this problem is to iterate through the input string and print each character followed by a space. This can be achieved using a loop that iterates over the length of the input string.
Here's a step-by-step breakdown:
- Initialize an empty string
resultto store the output. - Iterate through the input string using a loop.
- For each character in the input string, append the character followed by a space to the
resultstring. - Return the
resultstring.
Time complexity: O(n), where n is the length of the input string. Space complexity: O(n), as we are storing the output string with n characters.
Optimized Solutions
Java
public static String printWithSpace(String str) {
StringBuilder result = new StringBuilder();
for (char c : str.toCharArray()) {
result.append(c).append(" ");
}
return result.toString().trim();
}