Leetcode 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.

Example:

Input: [“cat”,”cats”,”catsdogcats”,”dog”,”dogcatsdog”,”hippopotamuses”,”rat”,”ratcatdogcat”]

Output: [“catsdogcats”,”dogcatsdog”,”ratcatdogcat”]

Explanation: “catsdogcats” can be concatenated by “cats”, “dog” and “cats”; 
“dogcatsdog” can be concatenated by “dog”, “cats” and “dog”;
”ratcatdogcat” can be concatenated by “rat”, “cat”, “dog” and “cat”.

Note:

  1. The number of elements of the given array will not exceed 10,000
  2. The length sum of elements in the given array will not exceed 600,000.
  3. All the input string will only include lower case letters.
  4. The returned elements order does not matter.

问题分析:
题意是找出所有可以由至少2个单词拼接而成的单词,可以一个一个的进行判断,即Word Break题。
而判断某个单词是否可以被其他单词拼接而成,可以按字符向后判断,判断从0到当前第i个字符是否可以拼接,如果前面从0到第j个字符可以拼接,同时word(j,i)也是一个单词,则从0到第i个字符可以拼接。
转移方程:
dp[i]=(dp[j]&&word(j,i)),j<,i
代码如下:

    public List<String> findAllConcatenatedWordsInADict(String[] words) {
        List<String> result=new ArrayList<String>();
        Set<String> set=new HashSet(Arrays.asList(words));
        for(String word: words){
            set.remove(word);
            if(breakWord(set,word))
                result.add(word);
            set.add(word);
        }
        return result;
    }
    public Boolean breakWord(Set<String> set, String word){
        if(word==null||word.length()==0)
            return false;
        int n=word.length();
        boolean[]dp=new boolean[n+1];
        dp[0]=true;
        for(int i=1;i<=n;i++){
            for(int j=0;j<i;j++){
                if(dp[j]&&set.contains(word.substring(j,i)))
                {
                    dp[i]=true;
                    break;
                }
            }
        }
        return dp[n];
    }

参考链接:https://segmentfault.com/a/1190000008233766

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值