前后拼接
难度:
标签:
题目描述
代码结果
运行时间: 35 ms, 内存: 16.1 MB
/*
* LeetCode 1181 - Before and After Puzzle
* Given a list of phrases, we need to return the list of all combinations of phrases where the last word of the first phrase matches the first word of the second phrase.
* The result should be sorted and duplicates should be removed.
*/
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SolutionStream {
public List<String> beforeAndAfterPuzzles(String[] phrases) {
return IntStream.range(0, phrases.length)
.boxed()
.flatMap(i -> IntStream.range(0, phrases.length)
.filter(j -> i != j)
.filter(j -> phrases[i].split(" ")[phrases[i].split(" ").length - 1].equals(phrases[j].split(" ")[0]))
.mapToObj(j -> phrases[i] + phrases[j].substring(phrases[j].split(" ")[0].length())))
.collect(Collectors.toSet())
.stream()
.sorted()
.collect(Collectors.toList());
}
}
解释
方法:
该题解的思路是使用两个字典来分别存储每个短语的前缀和后缀。然后,检查所有前缀和后缀是否有相同的部分,如果有,则将对应的短语拼接在一起。最后,返回排序后的结果集。
时间复杂度:
O(n^2m)
空间复杂度:
O(n^2m)
代码细节讲解
🦆
为什么选择使用两个字典来存储每个短语的前缀和后缀,而不是采用其他数据结构如数组或哈希表?
▷🦆
在处理前缀和后缀时,如何保证短语中的空格被正确处理,特别是对于包含多个空格或无空格的短语?
▷🦆
在找到相同的前缀和后缀后,为什么可以直接将两个短语拼接,而不需要考虑其他可能的字符串重叠或冲突?
▷🦆
该算法中`if s != p`的条件是为了避免什么问题?会不会有因此漏掉某些有效组合的情况?
▷