-
Notifications
You must be signed in to change notification settings - Fork 0
/
extraCharacters.txt
29 lines (26 loc) · 1.01 KB
/
extraCharacters.txt
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
2707. Extra Characters in a String
You are given a 0-indexed string s and a dictionary of words dictionary.
You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary.
There may be some extra characters in s which are not present in any of the substrings.
Return the minimum number of extra characters left over if you break up s optimally.
class Solution {
public:
int minExtraChar(string s, vector<string>& dictionary) {
unordered_set<string> dic;
int length = s.length();
for(auto i : dictionary){
dic.insert(i);
}
vector<int> delCount(length+1);
for(int j = 1 ; j <= length ; j++){
delCount[j] = 1 + delCount[j - 1];
for(int k = j ; k > 0 ; k--){
string word = s.substr(k-1,j-k+1);
if(dic.count(word)){
delCount[j] = min(delCount[j], delCount[k-1]);
}
}
}
return delCount[length];
}
};