word Break III

Give a dictionary of words and a sentence with all whitespace removed, return the number of sentences you can form by inserting whitespaces to the sentence so that each word can be found in the dictionary.

Example

Example1

Input:
"CatMat"
["Cat", "Mat", "Ca", "tM", "at", "C", "Dog", "og", "Do"]
Output: 3
Explanation:
we can form 3 sentences, as follows:
"CatMat" = "Cat" + "Mat"
"CatMat" = "Ca" + "tM" + "at"
"CatMat" = "C" + "at" + "Mat"

Example1

Input:
"a"
[]
Output: 0

Notice

Ignore case

思路:设dp[i][j]表示从i到j的string,能够被字典单词表达的种类有多少。
转移方程为:dp[i] [j] = 所有的dp[i][k] * dp[k+1][j] , i<=k<j的

根据定义,初始化就是 s.substring(i,j+1) 如果能查到,就是dp[i][j] = 1;

public class Solution {
    /*
     * @param : A string
     * @param : A set of word
     * @return: the number of possible sentences.
     */
    public int wordBreak3(String s, Set<String> dict) {
        if(s == null || dict == null) {
            return 0;
        }
        s = s.toLowerCase();
        dict = getLowerCase(dict);
        int n = s.length();
        int[][] dp = new int[n][n];
        //initial dp matrix;
        for(int i = 0; i < n; i++) {
            for(int j = i; j < n; j++) {
                String substr = s.substring(i, j+1);
                if(dict.contains(substr)) {
                    dp[i][j] = 1;
                }
            }
        }
        
        // calculate matrix;
        for(int i = 0; i < n; i++) {
            for(int j = i; j < n; j++) {
                for(int k = i; k < j; k++) {
                    dp[i][j] += dp[i][k] * dp[k+1][j];
                }
            }
        }
        return dp[0][n-1];
    }
    
    private Set<String> getLowerCase(Set<String> dict) {
        Set<String> set = new HashSet<String>();
        for(String str: dict) {
            set.add(str.toLowerCase());
        }
        return set;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值