Leetcode 2788. Split Strings by Separator
Given an array of strings words
and a character separator
, split each string in words
by the separator
and return all split substrings in the form of a flat list.
words
will only contain alphanumeric characters and the separator.words
array?
words
contains only the separator?
words
.separator
.import java.util.ArrayList;
import java.util.List;
public class SplitStringsBySeparator {
public static List<String> splitWordsBySeparator(String[] words, char separator) {
List<String> result = new ArrayList<>();
for (String word : words) {
String[] splitParts = word.split(Character.toString(separator));
for (String part : splitParts) {
result.add(part);
}
}
return result;
}
public static void main(String[] args) {
String[] words = {"hello.world", "java.is,fun", "split;by;separator"};
char separator = '.';
System.out.println(splitWordsBySeparator(words, separator));
separator = ',';
System.out.println(splitWordsBySeparator(words, separator));
separator = ';';
System.out.println(splitWordsBySeparator(words, separator));
}
}
n
is the total number of strings and m
is the average length of each string, then the complexity of this solution is (O(n \cdot m)), where n
is the number of strings and m
is the average length of each string. Since every string is processed exactly once, and each character is examined exactly once, it results in linear time complexity overall.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?