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;
}
}