878732. Print With Separator
Basic
Print With Separator
Summary
Given a list of strings, print them with a separator in between. The separator can be any string. This problem requires understanding of basic input-output operations and string manipulation.
Detailed Explanation
To solve this problem, we need to iterate over the list of strings and append the separator after each element except the last one. We'll use a loop to achieve this.
Here's the step-by-step breakdown:
- Initialize an empty string
resultthat will store the final output. - Iterate over the list of strings. For each string, append it to
result. - After appending each string, add the separator (if not at the last element).
- Finally, print the
result.
Time complexity: O(n), where n is the number of elements in the input list. Space complexity: O(n), as we're storing the output in a string.
Optimized Solutions
Java
public class PrintWithSeparator {
public static void print(String[] strings, String separator) {
for (int i = 0; i < strings.length; i++) {
System.out.print(strings[i]);
if (i < strings.length - 1) {
System.out.print(separator);
}
}
System.out.println();
}
}