算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 连接词,我们先来看题面:
https://leetcode-cn.com/problems/concatenated-words/
Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.
给你一个 不含重复 单词的字符串数组 words ,请你找出并返回 words 中的所有 连接词 。
连接词 定义为:一个完全由给定数组中的至少两个较短单词组成的字符串。
示例
示例 1:
输入:words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
输出:["catsdogcats","dogcatsdog","ratcatdogcat"]
解释:"catsdogcats" 由 "cats", "dog" 和 "cats" 组成;
"dogcatsdog" 由 "dog", "cats" 和 "dog" 组成;
"ratcatdogcat" 由 "rat", "cat", "dog" 和 "cat" 组成。
示例 2:
输入:words = ["cat","dog","catdog"]
输出:["catdog"]
解题
https://www.cnblogs.com/kexinxin/p/10280230.html
对于words中的每个单词w,我们定义一个数组dp[n+1],如果dp[i] == true,则表示w.substr(0, i)可以由words中的已有单词连接而成。那么状态转移方程就是:dp[i] = {dp[j] && w.substr(j + 1, i - j) is in words},其中j < i。最终检查dp[n]是否为true,如果是则将其加入结果集中。为了加速对words中的单词的查找,我们用一个哈希表来保存各个单词。这样时间复杂度可以降低到O(n * m^2),其中n是words中的单词的个数,m是每个单词的平均长度(或者最大长度?)。
import java.util.*;
class Solution {
public List<String> findAllConcatenatedWordsInADict(String[] words) {
Set<String> set=new HashSet<String>();
for(int i=0;i<words.length;i++){
set.add(words[i]);
}
List<String> res=new ArrayList<String>();
for(String word:words){
int n=word.length();
boolean[] dp=new boolean[n+1];
Arrays.fill(dp,false);
dp[0]=true;
for(int i=0;i<n;i++){
if(!dp[i]) continue;
for(int j=i+1;j<=n;j++){
if(j-i<n && set.contains(word.substring(i,j))){
dp[j]=true;
}
}
if(dp[n]){
res.add(word);
break;
}
}
}
return res;
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文:
LeetCode刷题实战462:最少移动次数使数组元素相等 II