[Hacker Rank] Abbreviation

Abbreviation

  • Time : O(nm)
  • Space : O(nm)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int dp[1001][1001];

bool helper(string& a, string& b, int i, int j) {
if(dp[i][j] != -1) return dp[i][j];
int& res = dp[i][j] = 0;
if(j == b.length()) {
for(int aa = i; aa < a.length(); aa++)
if(isupper(a[aa])) return res;
return res = 1;
}
if(i == a.length()) return res;
if(a[i] == b[j]) return res = helper(a, b, i + 1, j + 1);
if(islower(a[i]) and toupper(a[i]) == b[j]) return res = max(helper(a, b, i + 1, j + 1), helper(a, b, i + 1, j));
if(islower(a[i])) return res = helper(a, b, i + 1, j);
return res;
}

string abbreviation(string a, string b) {
memset(dp, -1, sizeof dp);
return helper(a, b, 0, 0) ? "YES" : "NO";
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/10/PS/HackerRank/abbr/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.