Skip to content

Commit ebc3544

Browse files
authored
Create 2707-extra-characters-in-a-string.cpp
1 parent 0416953 commit ebc3544

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
You are given a 0-indexed string s and a dictionary of words dictionary.
3+
You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary.
4+
There may be some extra characters in s which are not present in any of the substrings.
5+
6+
Return the minimum number of extra characters left over if you break up s optimally.
7+
8+
Ex. Input: s = "leetscode", dictionary = ["leet","code","leetcode"]
9+
Output: 1
10+
Explanation: We can break s in two substrings: "leet" from index 0 to 3 and "code" from index 5 to 8. There is only 1 unused character (at index 4), so we return 1.
11+
12+
Time : O(N^M) M = dictionary.size(), N = s.size()
13+
Space : O(N)
14+
*/
15+
16+
class Solution {
17+
public:
18+
int minExtraChar(string s, vector<string>& dictionary) {
19+
int n = s.size();
20+
vector<int> dp(n + 1, n);
21+
22+
dp[0] = 0;
23+
24+
for (int i = 1; i <= n; ++i) {
25+
for(int j = 0 ; j < dictionary.size() ; ++j) {
26+
int len = dictionary[j].size();
27+
if (i >= len && s.substr(i - len, len) == dictionary[j]) {
28+
dp[i] = min(dp[i], dp[i - len]);
29+
}
30+
}
31+
dp[i] = min(dp[i], dp[i - 1] + 1);
32+
}
33+
34+
return dp[n];
35+
}
36+
};

0 commit comments

Comments
 (0)