File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
longest-common-subsequence Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/longest-common-subsequence/submissions/1644426037/
3+ * @param {string } text1
4+ * @param {string } text2
5+ * @return {number }
6+ */
7+ var longestCommonSubsequence = function ( text1 , text2 ) {
8+ const m = text1 . length ;
9+ const n = text2 . length ;
10+
11+ // Create 2D array initialized with 0
12+ const dp = Array . from ( { length : m + 1 } , ( ) => Array ( n + 1 ) . fill ( 0 ) ) ;
13+
14+ // Fill the dp table
15+ for ( let i = 1 ; i <= m ; i ++ ) {
16+ for ( let j = 1 ; j <= n ; j ++ ) {
17+ if ( text1 [ i - 1 ] === text2 [ j - 1 ] ) {
18+ // Characters match
19+ dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] + 1 ;
20+ } else {
21+ // No match, take the max from left or top cell
22+ dp [ i ] [ j ] = Math . max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ;
23+ }
24+ }
25+ }
26+
27+ // The length of the longest common subsequence
28+ return dp [ m ] [ n ] ;
29+ } ;
You can’t perform that action at this time.
0 commit comments