472. Concatenated Words

题目

Given a list of words (without duplicates), please write a program that returns all 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.

我的想法

应该可以用dp做,但不知道怎样构建dp数组

解答

jiuzhang solution:
对每一个单词建立一个一维数组,存储该单词的substring(0, j) 是否在数组words中找到。如果dp[word.length] == true 则说明这个单词拼接单词

class Solution {
    public List<String> findAllConcatenatedWordsInADict(String[] words) {
        HashSet<String> dic = new HashSet<>();
        List<String> res = new ArrayList<>();
        for(String word : words) {
            dic.add(word);
        }
        for(String word : words) {
            if(word.length() == 0) {
                continue;
            }
            boolean[] dp = new boolean[word.length()+1];
            Arrays.fill(dp,false);
            dp[0] = true;
            for(int i = 0; i < word.length(); i++) {
                if(!dp[i]) {
                    continue;
                }
                for(int j = i + 1; j <= word.length(); j++) {
                	//避免把自己加进去
                    if(j-i != word.length() && dic.contains(word.substring(i, j))) {
                        dp[j] = true;
                    }
                }
                if(dp[word.length()]) {
                    res.add(word);
                    break;
                }
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值