Skip to content

Commit f685222

Browse files
authored
Merge pull request neetcode-gh#3331 from ACeldo1/2707-extra-characters-in-a-string
Create 2707-extra-characters-in-a-string.java
2 parents 8077f35 + 2e5ad96 commit f685222

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
Let N = length of string s, M = length of dictionary
3+
Time: O(N * M)
4+
Space: O(N)
5+
*/
6+
class Solution {
7+
public int minExtraChar(String s, String[] dictionary) {
8+
int n = s.length();
9+
int[] dp = new int[n+1];
10+
11+
Arrays.fill(dp, n);
12+
dp[0] = 0;
13+
14+
for (int i = 1; i <= n; ++i) {
15+
for (int j = 0; j < dictionary.length; ++j) {
16+
int len = dictionary[j].length();
17+
if (i >= len && s.substring(i - len, i).equals(dictionary[j])) {
18+
dp[i] = Math.min(dp[i], dp[i - len]);
19+
}
20+
}
21+
dp[i] = Math.min(dp[i], dp[i - 1] + 1);
22+
}
23+
24+
return dp[n];
25+
}
26+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy