Use this to learn the idea, then write your own version.
1class Solution {2 public boolean possiblyEquals(String s1, String s2) {3 Map<Integer, Boolean>[][] mem = new Map[s1.length() + 1][s2.length() + 1];4 for (int i = 0; i <= s1.length(); ++i)5 for (int j = 0; j <= s2.length(); ++j)6 mem[i][j] = new HashMap<>();7 return f(s1, s2, 0, 0, 0, mem);8 }9 10 11 12 13 14 private boolean f(final String s1, final String s2, int i, int j, int paddingDiff,15 Map<Integer, Boolean>[][] mem) {16 if (mem[i][j].containsKey(paddingDiff))17 return mem[i][j].get(paddingDiff);18 if (i == s1.length() && j == s2.length())19 return paddingDiff == 0;20 if (i < s1.length() && Character.isDigit(s1.charAt(i))) {21 22 final int nextLetterIndex = getNextLetterIndex(s1, i);23 for (final int num : getNums(s1.substring(i, nextLetterIndex)))24 if (f(s1, s2, nextLetterIndex, j, paddingDiff + num, mem))25 return true;26 } else if (j < s2.length() && Character.isDigit(s2.charAt(j))) {27 28 final int nextLetterIndex = getNextLetterIndex(s2, j);29 for (final int num : getNums(s2.substring(j, nextLetterIndex)))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.charAt(i) == s2.charAt(j))43 return f(s1, s2, i + 1, j + 1, 0, mem);44 }45 mem[i][j].put(paddingDiff, false);46 return false;47 }48 49 private int getNextLetterIndex(final String s, int i) {50 int j = i;51 while (j < s.length() && Character.isDigit(s.charAt(j)))52 ++j;53 return j;54 }55 56 private List<Integer> getNums(final String s) {57 List<Integer> nums = new ArrayList<>(List.of(Integer.parseInt(s)));58 if (s.length() == 2) {59 nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 2)));60 } else if (s.length() == 3) {61 nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 3)));62 nums.add(Integer.parseInt(s.substring(0, 2)) + Integer.parseInt(s.substring(2, 3)));63 nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 2)) +64 Integer.parseInt(s.substring(2, 3)));65 }66 return nums;67 }68}69