Use this to learn the idea, then write your own version.
1class Solution {2 public:3 bool possiblyEquals(string s1, string s2) {4 vector<vector<unordered_map<int, bool>>> mem(5 s1.length() + 1, vector<unordered_map<int, bool>>(s2.length() + 1));6 return f(s1, s2, 0, 0, 0, mem);7 }8 9 private:10 11 12 13 14 bool f(const string& s1, const string& s2, int i, int j, int paddingDiff,15 vector<vector<unordered_map<int, bool>>>& mem) {16 if (const auto it = mem[i][j].find(paddingDiff); it != mem[i][j].cend())17 return it->second;18 if (i == s1.length() && j == s2.length())19 return paddingDiff == 0;20 if (i < s1.length() && isdigit(s1[i])) {21 22 const int nextLetterIndex = getNextLetterIndex(s1, i);23 for (const int num : getNums(s1.substr(i, nextLetterIndex - i)))24 if (f(s1, s2, nextLetterIndex, j, paddingDiff + num, mem))25 return true;26 } else if (j < s2.length() && isdigit(s2[j])) {27 28 const int nextLetterIndex = getNextLetterIndex(s2, j);29 for (const int num : getNums(s2.substr(j, nextLetterIndex - j)))30 if (f(s1, s2, i, nextLetterIndex, paddingDiff - num, mem))31 return true;32 } else if (paddingDiff > 0) {33 34 if (j < s2.length())35 return f(s1, s2, i, j + 1, paddingDiff - 1, mem);36 } else if (paddingDiff < 0) {37 38 if (i < s1.length())39 return f(s1, s2, i + 1, j, paddingDiff + 1, mem);40 } else { 41 42 if (i < s1.length() && j < s2.length() && s1[i] == s2[j])43 return f(s1, s2, i + 1, j + 1, 0, mem);44 }45 return mem[i][j][paddingDiff] = false;46 }47 48 int getNextLetterIndex(const string& s, int i) {49 int j = i;50 while (i < s.length() && isdigit(s[j]))51 ++j;52 return j;53 }54 55 vector<int> getNums(const string& s) {56 vector<int> nums{stoi(s)};57 if (s.length() == 2) {58 nums.push_back(stoi(s.substr(0, 1)) + stoi(s.substr(1, 1)));59 } else if (s.length() == 3) {60 nums.push_back(stoi(s.substr(0, 1)) + stoi(s.substr(1, 2)));61 nums.push_back(stoi(s.substr(0, 2)) + stoi(s.substr(2, 1)));62 nums.push_back(stoi(s.substr(0, 1)) + stoi(s.substr(1, 1)) +63 stoi(s.substr(2, 1)));64 }65 return nums;66 }67};68