1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public int respace(String[] dictionary, String sentence) { Set<String> wordSet = new HashSet<>(Arrays.asList(dictionary));
int[] dp = new int[sentence.length() + 1];
for (int i = 1; i <= sentence.length(); i++) { dp[i] = dp[i - 1] + 1; for (int j = 0; j < i; j++) { if (wordSet.contains(sentence.substring(j, i))) { dp[i] = Math.min(dp[i], dp[j]); } } }
return dp[sentence.length()]; } }
|