-
Notifications
You must be signed in to change notification settings - Fork 16
/
SplitStringsBySeparator.java
40 lines (37 loc) · 1.23 KB
/
SplitStringsBySeparator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// https://leetcode.com/problems/split-strings-by-separator
// W: number of words
// s: string in words
// T: O(W * |s|)
// S: O(W * |s|)
import java.util.ArrayList;
import java.util.List;
public class SplitStringsBySeparator {
public List<String> splitWordsBySeparator(List<String> words, char separator) {
final List<String> result = new ArrayList<>();
for (String word : words) {
final List<String> splitStrings = split(word, separator);
for (String split : splitStrings) {
if (!split.isEmpty()) {
result.add(split);
}
}
}
return result;
}
private List<String> split(String string, char separator) {
final List<String> result = new ArrayList<>();
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < string.length() ; i++) {
if (string.charAt(i) == separator) {
result.add(builder.toString());
builder = new StringBuilder();
} else {
builder.append(string.charAt(i));
}
}
if (!builder.isEmpty()) {
result.add(builder.toString());
}
return result;
}
}