Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 4251626

Browse files
committed
Add solution #2707
1 parent f97b1a2 commit 4251626

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1998,6 +1998,7 @@
19981998
2704|[To Be Or Not To Be](./solutions/2704-to-be-or-not-to-be.js)|Easy|
19991999
2705|[Compact Object](./solutions/2705-compact-object.js)|Medium|
20002000
2706|[Buy Two Chocolates](./solutions/2706-buy-two-chocolates.js)|Easy|
2001+
2707|[Extra Characters in a String](./solutions/2707-extra-characters-in-a-string.js)|Medium|
20012002
2715|[Timeout Cancellation](./solutions/2715-timeout-cancellation.js)|Easy|
20022003
2721|[Execute Asynchronous Functions in Parallel](./solutions/2721-execute-asynchronous-functions-in-parallel.js)|Medium|
20032004
2722|[Join Two Arrays by ID](./solutions/2722-join-two-arrays-by-id.js)|Medium|
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 2707. Extra Characters in a String
3+
* https://leetcode.com/problems/extra-characters-in-a-string/
4+
* Difficulty: Medium
5+
*
6+
* You are given a 0-indexed string s and a dictionary of words dictionary. You have to break
7+
* s into one or more non-overlapping substrings such that each substring is present in
8+
* dictionary. There may be some extra characters in s which are not present in any of the
9+
* substrings.
10+
*
11+
* Return the minimum number of extra characters left over if you break up s optimally.
12+
*/
13+
14+
/**
15+
* @param {string} s
16+
* @param {string[]} dictionary
17+
* @return {number}
18+
*/
19+
var minExtraChar = function(s, dictionary) {
20+
const n = s.length;
21+
const dp = new Array(n + 1).fill(Infinity);
22+
dp[0] = 0;
23+
const dictSet = new Set(dictionary);
24+
25+
for (let i = 1; i <= n; i++) {
26+
dp[i] = dp[i - 1] + 1;
27+
for (let j = 0; j < i; j++) {
28+
if (dictSet.has(s.slice(j, i))) {
29+
dp[i] = Math.min(dp[i], dp[j]);
30+
}
31+
}
32+
}
33+
34+
return dp[n];
35+
};

0 commit comments

Comments
 (0)