Easy
题目描述
给定一个字符串数组 words 和一个字符 separator,请按 separator 分割 words 中的每个字符串。
返回一个字符串数组,包含分割后形成的新字符串,不包括空字符串。
注意:
separator用于确定分割的位置,但它不作为结果字符串的一部分。- 一次分割可能产生两个以上的字符串。
- 结果字符串必须保持与初始给定的相同顺序。
示例 1:
输入:words = ["one.two.three","four.five","six"], separator = "."
输出:["one","two","three","four","five","six"]
解释:在这个例子中,我们按如下方式分割:
"one.two.three" 分割为 "one", "two", "three"
"four.five" 分割为 "four", "five"
"six" 分割为 "six"
因此,结果数组是 ["one","two","three","four","five","six"]。
示例 2:
输入:words = ["$easy$","$problem$"], separator = "$"
输出:["easy","problem"]
解释:在这个例子中,我们按如下方式分割:
"$easy$" 分割为 "easy"(排除空字符串)
"$problem$" 分割为 "problem"(排除空字符串)
因此,结果数组是 ["easy","problem"]。
示例 3:
输入:words = ["|||"], separator = "|"
输出:[]
解释:在这个例子中,"|||" 的分割结果只包含空字符串,所以我们返回空数组 []。
约束条件:
1 <= words.length <= 1001 <= words[i].length <= 20words[i]中的字符要么是小写英文字母,要么是字符串".,|$#@"中的字符(不包括引号)separator是字符串".,|$#@"中的一个字符(不包括引号)
解题思路
这道题要求按指定分隔符分割字符串数组,并过滤掉空字符串。思路比较直观:
基本思路:
- 遍历输入的字符串数组
words - 对每个字符串按
separator进行分割 - 将分割后的非空字符串添加到结果数组中
- 返回最终的结果数组
实现要点:
- 使用语言内置的字符串分割函数
- 在添加分割结果时需要检查是否为空字符串
- 保持原有的顺序不变
算法步骤:
- 初始化结果数组
- 对于
words中的每个字符串word:- 按
separator分割word - 遍历分割结果,将非空字符串添加到结果数组
- 按
- 返回结果数组
这种方法利用了各种编程语言内置的字符串分割功能,代码简洁且易于理解。时间复杂度主要取决于字符串的总长度和分割操作的复杂度。
代码实现
class Solution {
public:
vector<string> splitWordsBySeparator(vector<string>& words, char separator) {
vector<string> result;
for (const string& word : words) {
string current = "";
for (char c : word) {
if (c == separator) {
if (!current.empty()) {
result.push_back(current);
current = "";
}
} else {
current += c;
}
}
if (!current.empty()) {
result.push_back(current);
}
}
return result;
}
};
class Solution:
def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]:
result = []
for word in words:
parts = word.split(separator)
for part in parts:
if part: # 只添加非空字符串
result.append(part)
return result
public class Solution {
public IList<string> SplitWordsBySeparator(IList<string> words, char separator) {
List<string> result = new List<string>();
foreach (string word in words) {
string[] parts = word.Split(separator);
foreach (string part in parts) {
if (!string.IsNullOrEmpty(part)) {
result.Add(part);
}
}
}
return result;
}
}
/**
* @param {string[]} words
* @param {character} separator
* @return {string[]}
*/
var splitWordsBySeparator = function(words, separator) {
const result = [];
for (const word of words) {
const parts = word.split(separator);
for (const part of parts) {
if (part.length > 0) {
result.push(part);
}
}
}
return result;
};
复杂度分析
| 复杂度类型 | 复杂度 | 说明 |
|---|---|---|
| 时间复杂度 | O(n) | 其中 n 是所有字符串的字符总数,需要遍历每个字符进行分割 |
| 空间复杂度 | O(n) | 存储分割后的结果字符串,最坏情况下每个字符都是一个单独的字符串 |