LeetCode-in-Java

2788. Split Strings by Separator

Easy

Given an array of strings words and a character separator, split each string in words by separator.

Return an array of strings containing the new strings formed after the splits, excluding empty strings.

Notes

Example 1:

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”].

Example 2:

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”].

Example 3:

Input: words = [”|||”], separator = “|”

Output: []

Explanation:

In this example the resulting split of “|||” will contain only empty strings, so we return an empty array [].

Constraints:

Solution

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<String> splitWordsBySeparator(List<String> words, char separator) {
        List<String> list = new ArrayList<>();
        for (String str : words) {
            int si = 0;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == separator) {
                    if (i > si) {
                        list.add(str.substring(si, i));
                    }
                    si = i + 1;
                }
            }
            if (si != str.length()) {
                list.add(str.substring(si, str.length()));
            }
        }
        return list;
    }
}