forked from codereport/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamic_Programming_04_Abbrevition.cpp
More file actions
63 lines (49 loc) · 1.31 KB
/
Copy pathDynamic_Programming_04_Abbrevition.cpp
File metadata and controls
63 lines (49 loc) · 1.31 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// code_report Solution
// Solution 1:
// https://youtu.be/DW92IHf8KK8
#include <unordered_set>
#include <algorithm>
#include <string>
using namespace std;
void rec(string A, string B);
unordered_set<string> memo;
bool possible;
auto abbreviation(string a, string b) {
possible = false;
memo.clear();
rec(a, b);
return possible ? "YES" : "NO";
}
void rec(string A, string B) {
if (possible || A.size() < B.size()) return;
if (B.empty()) {
if (all_of(A.begin(), A.end(), [](auto e) { return islower(e); }))
possible = true;
return;
}
auto p = memo.insert(A + '#' + B);
if (!p.second) return; // return if A#B already in set
auto fc = A[0]; // first char
A.erase(0, 1);
if (islower(fc)) rec(A, B);
if (toupper(fc) != B[0]) return;
B.erase(0, 1);
rec(A, B);
return;
}
// Solution 2:
// https://youtu.be/ViILdd8495M
auto abbreviation(string a, string b) {
int n = a.size();
int m = b.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1));
dp[0][0] = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= m; j++) {
if (!dp[i][j]) continue;
if (j < m && toupper(a[i]) == b[j]) dp[i + 1][j + 1] = 1;
if (!isupper(a[i])) dp[i + 1][j ] = 1;
}
}
return (dp[n][m] ? "YES\n" : "NO\n");
}