Skip to content

2788. Split Strings by Separator 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  vector<string> splitWordsBySeparator(vector<string>& words, char separator) {
    vector<string> ans;

    for (const string& word : words) {
      istringstream iss(word);
      for (string word; getline(iss, word, separator);)
        if (!word.empty())
          ans.push_back(word);
    }

    return ans;
  }
};
1
2
3
4
5
6
7
8
public class Solution {
  public List<String> splitWordsBySeparator(List<String> words, char separator) {
    return words.stream()
        .flatMap(word -> Arrays.stream(word.split("\\" + separator)))
        .filter(word -> !word.isEmpty())
        .collect(Collectors.toList());
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def splitWordsBySeparator(
      self,
      words: list[str],
      separator: str,
  ) -> list[str]:
    return [splitWord
            for word in words
            for splitWord in word.split(separator)
            if splitWord]