Leetcode Problem 2060. Check if an Original String Exists Given Two Encoded Strings

2060. Check if an Original String Exists Given Two Encoded Strings

Leetcode Solutions

Dynamic Programming with Memoization

  1. Define a recursive function dfs that takes the current indices i and j of s1 and s2, respectively, and the current difference diff as arguments.
  2. If both i and j have reached the end of their respective strings and diff is zero, return true.
  3. If the result for the current state (i, j, diff) is already computed, return the stored result.
  4. If i points to a digit in s1, iterate through all possible lengths that the numeric substring starting at i could represent, and recursively call dfs with the new index and adjusted diff.
  5. Similarly, if j points to a digit in s2, iterate through all possible lengths that the numeric substring starting at j could represent, and recursively call dfs with the new index and adjusted diff.
  6. If diff is zero and both i and j point to letters, compare the letters. If they match, recursively call dfs with the next indices.
  7. If diff is positive, recursively call dfs with the next index of s1 and diff decremented by one.
  8. If diff is negative, recursively call dfs with the next index of s2 and diff incremented by one.
  9. Store the result of the current state in the memoization table before returning it.
  10. Initialize the memoization table and call dfs starting with indices 0, 0, and diff 0.
UML Thumbnail

Backtracking with Pruning

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...