按分隔符拆分字符串
难度:
标签:
题目描述
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
separator
is used to determine where the split should occur, but it is not included as part of the resulting strings.- A split may result in more than two strings.
- The resulting strings must maintain the same order as they were initially given.
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:
1 <= words.length <= 100
1 <= words[i].length <= 20
- characters in
words[i]
are either lowercase English letters or characters from the string".,|$#@"
(excluding the quotes) separator
is a character from the string".,|$#@"
(excluding the quotes)
代码结果
运行时间: 19 ms, 内存: 16.1 MB
/*
* 思路:
* 1. 使用 Java Stream 流操作遍历字符串数组 words。
* 2. 对每个字符串使用 split 方法进行拆分。
* 3. 使用 flatMap 展平拆分后的字符串数组。
* 4. 使用 filter 去除空字符串。
* 5. 使用 collect 将结果收集到 List 中。
*/
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Solution {
public List<String> splitWordsStream(String[] words, String separator) {
return Arrays.stream(words)
.flatMap(word -> Arrays.stream(word.split(separator)))
.filter(splitWord -> !splitWord.isEmpty())
.collect(Collectors.toList());
}
}
解释
方法:
题解采用了列表推导式来处理问题,通过两层循环来实现。首先,外层循环遍历输入的字符串数组 `words`,内层循环则是对每个字符串使用 `split` 方法按照 `separator` 进行拆分。`split` 方法会返回一个列表,其中包含分割后的子字符串。如果分割后的子字符串非空(即 `if s` 部分),则将其包含在最终的结果列表中。这种方法直接利用 Python 的内建字符串处理功能,简洁且高效。
时间复杂度:
O(L)
空间复杂度:
O(L)
代码细节讲解
🦆
在此题解中,列表推导式的使用是否会影响代码的可读性,尤其是当涉及两层循环时?
▷🦆
此算法如何处理包含连续分隔符的情况,例如 'one..two.three',是否会产生空字符串,它们是如何被处理的?
▷🦆
如果输入数组 `words` 中的元素为空字符串,例如 ['', 'one.two'], 那么这种情况下的输出是什么?
▷