Given two strings 's1' and 's2', find the length of the longest common substring.
This algorithm uses memoization to improve performance. It's same as the recursive version of Find longest common substring, but with a special 'cache' to store results. The 'cache key' is crucial. It's how we identify and store past results. Sometimes we need one key, sometimes multiple keys. We add code to:
cache = {} def count(s1, s2): if s2 == "": return 0 global cache if s2 not in cache: if s2 in s1: cache[s2] = len(s2) else: cache[s2] = max(count(s1, s2[1:]), count(s1, s2[:-1])) return cache[s2] s1 = "QuestionOfTheDay" s2 = "NewQuestion" print(count(s1, s2))
const cache = {} function count(s1, s2) { if (s2 === "") { return 0; } if (cache[s2] === undefined) { if (s1.indexOf(s2) >= 0) { cache[s2] = s2.length; } else { cache[s2] = Math.max(count(s1, s2.slice(1)), count(s1, s2.slice(0, -1))); } } return cache[s2]; } const s1 = "QuestionOfTheDay"; const s2 = "NewQuestion"; console.log(count(s1, s2));