LeetCode 题解工作台
按分隔符拆分字符串
给你一个字符串数组 words 和一个字符 separator ,请你按 separator 拆分 words 中的每个字符串。 返回一个由拆分后的新字符串组成的字符串数组, 不包括空字符串 。 注意 separator 用于决定拆分发生的位置,但它不包含在结果字符串中。 拆分可能形成两个以上的字符…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
我们遍历字符串数组 ,对于每个字符串 ,我们使用 `separator` 作为分隔符进行拆分,如果拆分后的字符串不为空,则将其加入答案数组。 时间复杂度 $O(n \times m)$,空间复杂度 ,其中 是字符串数组 的长度,而 是字符串数组 中字符串的最大长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你一个字符串数组 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是字符串".,|$#@"中的某个字符(不包括引号)
解题思路
方法一:模拟
我们遍历字符串数组 ,对于每个字符串 ,我们使用 separator 作为分隔符进行拆分,如果拆分后的字符串不为空,则将其加入答案数组。
时间复杂度 ,空间复杂度 ,其中 是字符串数组 的长度,而 是字符串数组 中字符串的最大长度。
class Solution:
def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]:
return [s for w in words for s in w.split(separator) if s]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n * m) where n is the number of strings and m is the average string length, due to iterating and splitting each string. Space complexity is O(total number of resulting substrings) as we store all non-empty parts. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for handling consecutive separators correctly.
- question_mark
Ensure empty strings are not included in the result.
- question_mark
Check if the solution maintains the original order of words and splits.
常见陷阱
外企场景- error
Including empty strings after splitting at consecutive separators.
- error
Not preserving the order of strings after flattening all splits.
- error
Using complex nested loops instead of simple iteration and split.
进阶变体
外企场景- arrow_right_alt
Split strings by multiple different separator characters instead of one.
- arrow_right_alt
Return only substrings of a certain minimum length after splitting.
- arrow_right_alt
Split a single long string multiple times using an array of separators.