2788. Split Strings by Separator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public List<String> splitWordsBySeparator(List<String> words, char separator) {
List<String> resultList = new ArrayList<>();

for (String word : words) {
int i = 0; // [i, j)
for (int j = 0; j < word.length(); j++) {
// 分隔符与字符串末尾字符分开处理是因为右边界不一样
if (word.charAt(j) == separator) {
if (i < j) { // 防止收集到空字符串
resultList.add(word.substring(i, j));
}
i = j + 1;
} else if (j == word.length() - 1) { // 字符串末尾且不是 separator
resultList.add(word.substring(i, word.length())); // 注意此处的右边界是 word.length
}
}
}

return resultList;
}
}

References

2788. Split Strings by Separator