​LeetCode刷题实战472:连接词

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-460题汇总,希望对你有点帮助!

LeetCode刷题实战461:汉明距离

LeetCode刷题实战462:最少移动次数使数组元素相等 II

LeetCode刷题实战463:岛屿的周长

LeetCode刷题实战464:我能赢吗

LeetCode刷题实战465:最优账单平衡

LeetCode刷题实战466:统计重复个数

LeetCode刷题实战467:环绕字符串中唯一的子字符串

LeetCode刷题实战468:验证IP地址

LeetCode刷题实战469:凸多边形

LeetCode刷题实战470:用 Rand7() 实现 Rand10()

LeetCode刷题实战471:编码最短长度的字符串

f6f370b35e1b6f60a12d1bb5650e5e58.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值