-
Notifications
You must be signed in to change notification settings - Fork 3
/
2707.cpp
27 lines (25 loc) · 861 Bytes
/
2707.cpp
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
class Solution {
public:
int minExtraChar(string s, vector<string>& dictionary) {
int n = s.size();
vector<vector<bool>> matchMap(n, vector<bool>(n + 1, false));
unordered_set<string> st(dictionary.begin(), dictionary.end());
for (int i = 0; i < n; ++i) {
for (int j = 1; i + j <= n; ++j) {
string substring = s.substr(i, j);
if (st.count(substring)) matchMap[i][j] = true;
}
}
vector<int> dp(n + 1, INT_MAX);
dp[0] = 0;
for (int i = 0; i < n; ++i) {
dp[i + 1] = dp[i] + 1;
for (int j = 1; i + 1 - j >= 0; ++j) {
if (matchMap[i + 1 - j][j]) {
dp[i + 1] = min(dp[i + 1], dp[i + 1 - j]);
};
}
}
return dp[n];
}
};