1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { public int minExtraChar(String s, String[] dictionary) { int n = s.length(); int[] dp = new int[n + 1]; for (int i = 0; i < n; i++) { dp[i + 1] = dp[i] + 1; for (String word : dictionary) { if (this.isSameFromLast(s, i, word)) { dp[i + 1] = Math.min(dp[i + 1], dp[i - word.length() + 1]); } } } return dp[n]; }
private boolean isSameFromLast(String str, int endIndex, String subStr) { int n1 = str.length(); int n2 = subStr.length(); if (n2 > endIndex + 1) { return false; } int i = endIndex; int j = n2 - 1; while (j >= 0) { if (str.charAt(i) != subStr.charAt(j)) { return false; } i--; j--; } return true; }
}
|