Leetcode 2788. Split Strings by Separator
Given an array of strings words
and a character separator
, split each string in words
by separator
and return all the strings “after splitting” in the same order they appear in. You may return the strings in any order.
Input: words = ["one.two.three", "four.five", "six"], separator = '.'
Output: ["one", "two", "three", "four", "five", "six"]
Q: Are we allowed to use built-in string splitting functions? A: For this problem, you can assume that you need to implement your own function to split the strings.
Q: Can the separator character be any character? A: Yes, it can be any character.
Q: How should empty segments be treated? A: The behavior for empty segments isn’t clearly stated, but typically we should return such segments unless otherwise specified.
result
to store the substrings after splitting.words
:
result
vector.result
vector.Here’s one way to implement this:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> splitStringsBySeparator(vector<string>& words, char separator) {
vector<string> result;
// Iterate over each word in the list
for (const string& word : words) {
size_t begin = 0;
size_t end = word.find(separator);
// Loop to find all separators in the word
while (end != string::npos) {
result.push_back(word.substr(begin, end - begin));
begin = end + 1;
end = word.find(separator, begin);
}
// Add the last or the only segment
result.push_back(word.substr(begin));
}
return result;
}
int main() {
vector<string> words = {"one.two.three", "four.five", "six"};
char separator = '.';
vector<string> result = splitStringsBySeparator(words, separator);
cout << "Result: ";
for (const string& str : result) {
cout << str << " ";
}
cout << endl;
return 0;
}
words
and ( M ) is the number of separators.
The overall efficiency is effectively linear in terms of the total input size combined with the number of separators. This approach should be optimal for most realistic input sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?