(text1, text2 string, text1Idx, text2Idx int, memo [][]int)
| 43 | } |
| 44 | |
| 45 | func lcs(text1, text2 string, text1Idx, text2Idx int, memo [][]int) int { |
| 46 | // if text1 or text 2 are empty, there is no longest common substring |
| 47 | if text1Idx == 0 || text2Idx == 0 { |
| 48 | return 0 |
| 49 | } |
| 50 | |
| 51 | // Aha! Use of 2d array for memoization concept sticking for me. |
| 52 | // I tried to use two different keys by my 1st and 2nd intuition. |
| 53 | // Found out that the 2d array suites this need perfectly. |
| 54 | // The row (text1Idx) and column (text2Idx) can be the key to the location |
| 55 | // in the 2d array. This is much faster and very useful. |
| 56 | |
| 57 | //key := text1Idx * 10 + text2Idx (incorrect) |
| 58 | //key := text1[0:text1Idx] + text2[0:text2Idx] (OOM on leetcode) |
| 59 | if memo[text1Idx][text2Idx] != -1 { |
| 60 | return memo[text1Idx][text2Idx] |
| 61 | } |
| 62 | |
| 63 | // if text1 and text2 at their indices are equal, then they are |
| 64 | // a part of a common subsequence |
| 65 | if text1[text1Idx-1] == text2[text2Idx-1] { |
| 66 | memo[text1Idx][text2Idx] = 1 + lcs(text1, text2, text1Idx-1, text2Idx-1, memo) |
| 67 | return memo[text1Idx][text2Idx] |
| 68 | } |
| 69 | |
| 70 | // find the max by choosing to clip off the last character |
| 71 | // on (text1, not text2) and (not text1, text2) |
| 72 | l1 := lcs(text1, text2, text1Idx-1, text2Idx, memo) |
| 73 | l2 := lcs(text1, text2, text1Idx, text2Idx-1, memo) |
| 74 | memo[text1Idx][text2Idx] = int(math.Max(float64(l1), float64(l2))) |
| 75 | return memo[text1Idx][text2Idx] |
| 76 | } |
| 77 | |
| 78 | // Note: first attempt that passed test cases in description examples. |
| 79 | // Isn't correct in all cases. |
no outgoing calls
no test coverage detected