Given two strings s1 and s2 of lengths m and n, find the minimum number of edits (operations) to convert "s1" into "s2" using operations of insert, remove or replace of a char.
Building upon understanding of Find the minimum number of edits (Memoization). Pay attention to the cache. Tabulation essentially reconstructs the cache.
Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.
The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.
def count(s1, s2): cache = [[0] * (len(s2) + 1) for _ in range(len(s1) + 1)] for i in range(len(s1) + 1): cache[i][0] = i for j in range(len(s2) + 1): cache[0][j] = j for i in range(1, len(s1) + 1): for j in range(1, len(s2) + 1): if s1[i - 1] == s2[j - 1]: cache[i][j] = cache[i - 1][j - 1] else: cache[i][j] = 1 + min(cache[i][j - 1], cache[i - 1][j], cache[i - 1][j - 1]) return cache[len(s1)][len(s2)] s1 = 'sunday' s2 = 'saturday' print(count(s1, s2))
function count(s1, s2) { const cache = Array.from(Array(s1.length + 1), () => Array(s2.length + 1).fill(0)); for (let i = 0; i < s1.length + 1; i++) { cache[i][0] = i; } for (let j = 0; j < s2.length + 1; j++) { cache[0][j] = j; } for (let i = 1; i < s1.length + 1; i++) { for (let j = 1; j < s2.length + 1; j++) { if (s1[i - 1] == s2[j - 1]) { cache[i][j] = cache[i - 1][j - 1]; } else { cache[i][j] = 1 + Math.min(cache[i][j - 1], cache[i - 1][j], cache[i - 1][j - 1]); } } } return cache[s1.length][s2.length]; } const s1 = 'sunday'; const s2 = 'saturday'; console.log(count(s1, s2));