Input: words =["one.two.three","four.five","six"], separator ="."Output: ["one","two","three","four","five","six"]Explanation: In this example we split as follows:"one.two.three" splits into "one","two","three""four.five" splits into "four","five""six" splits into "six"Hence, the resulting array is["one","two","three","four","five","six"].
Input: words =["$easy$","$problem$"], separator ="$"Output: ["easy","problem"]Explanation: In this example we split as follows:"$easy$" splits into "easy"(excluding empty strings)"$problem$" splits into "problem"(excluding empty strings)Hence, the resulting array is["easy","problem"].
Input: words =["|||"], separator ="|"Output: []Explanation: In this example the resulting split of "|||" will contain only empty strings, so we return an empty array [].
Splitting each string by the separator and removing empty results gives the required output. This works because the split operation naturally handles multiple separators and preserves order.
funcsplitWordsBySeparator(words []string, seprune) []string {
varans []stringfor_, w:=rangewords {
cur:=""for_, c:=rangew {
ifc==sep {
if len(cur) > 0 {
ans = append(ans, cur)
}
cur = "" } else {
cur+= string(c)
}
}
if len(cur) > 0 {
ans = append(ans, cur)
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
public List<String>splitWordsBySeparator(List<String> words, char sep) {
List<String> ans =new ArrayList<>();
for (String w : words) {
StringBuilder cur =new StringBuilder();
for (char c : w.toCharArray()) {
if (c == sep) {
if (cur.length() > 0) ans.add(cur.toString());
cur.setLength(0);
} else {
cur.append(c);
}
}
if (cur.length() > 0) ans.add(cur.toString());
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
funsplitWordsBySeparator(words: List<String>, sep: Char): List<String> {
val ans = mutableListOf<String>()
for (w in words) {
var cur = ""for (c in w) {
if (c == sep) {
if (cur.isNotEmpty()) ans.add(cur)
cur = "" } else {
cur += c
}
}
if (cur.isNotEmpty()) ans.add(cur)
}
return ans
}
}
1
2
3
4
5
defsplitWordsBySeparator(words: list[str], sep: str) -> list[str]:
ans = []
for w in words:
ans += [x for x in w.split(sep) if x]
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnsplit_words_by_separator(words: Vec<String>, sep: char) -> Vec<String> {
letmut ans = Vec::new();
for w in words {
for part in w.split(sep) {
if!part.is_empty() {
ans.push(part.to_string());
}
}
}
ans
}
}