Given string str, find the minimum number of characters to be inserted to make it a palindrome.
Building upon understanding of Minimum insertions to form a palindrome (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(s): cache = [[0] * len(s) for _ in range(len(s))] for i in range(2, len(s) + 1): for j in range(len(s) - i + 1): k = j + i - 1 cache[j][k] = cache[j + 1][k - 1] if s[j] == s[k] else min(cache[j + 1][k], cache[j][k - 1]) + 1 return cache[0][len(s) - 1] s = 'abcd' print(count(s))
function count(s) { const cache = Array.from(Array(s.length), () => Array(s.length).fill(0)); for (let i = 2; i < s.length + 1; i++) { for (let j = 0; j < s.length - i + 1; j++) { const k = j + i - 1; cache[j][k] = (s[j] == s[k]) ? cache[j + 1][k - 1] : Math.min(cache[j + 1][k], cache[j][k - 1]) + 1; } } return cache[0][s.length - 1]; } const str = 'abcd'; console.log(count(str));