HackerRank/Algorithm/Dynamic Programming/Abbreviation

Problem Summary

Given two strings, A and B, determine if it is possible that B is an abbreviation for A.

Solution

This is a classic dynamic programming problem.

Let f[i,j] = true if the first j letters of B can be an abbreviation for the first i letters of A, and f[i,j] = false otherwise.

Code

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
#include <iostream>
#include <climits>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
int main()
{
int T;
cin >> T;
while(T)
{
T--;
string a, b;
cin >> a >> b;
int n = a.length(), m = b.length();
if (n < m) {
cout << "NO" << endl;
continue;
}
vector<vector<bool>> f(n+1, vector<bool>(m+1));
f[0][0] = true;
for (int i = 1; i <= n && islower(a[i-1]); ++i)
f[i][0] = true;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= min(m, i); ++j) {
if (islower(a[i-1]))
f[i][j] = f[i][j] || f[i-1][j];
if (toupper(a[i-1]) == b[j-1])
f[i][j] = f[i][j] || f[i-1][j-1];
}
}
if(f[n][m])
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}