longest common subsequence javascript code example
Example 1: find length of longest string in array javascript
const findLongest = words => Math.max(...(words.map(el => el.length)));
// Example
findLongest(['always','look','on','the','bright','side','of','life']); // 6
Example 2: longest common subsequence codefroces
using namespace std;
const int MAX = 1001;
int dp[MAX][MAX];
bool visited[MAX][MAX];
int x, y;
string s1, s2;
int lcs(int i, int j)
{
if(i == x || j == y)
return 0;
if(visited[i][j])
return dp[i][j];
visited[i][j] = true;
int ans = 0;
if(s1[i] == s2[j])
{
ans = max(ans, 1+lcs(i+1, j+1));
}
else
{
ans = max(ans, lcs(i+1, j));
ans = max(ans, lcs(i, j+1));
}
dp[i][j] = ans;
return ans;
}
int main()
{
cin >> x >> y;
cin >> s1 >> s2;
for(int i=0; i<=x; i++)
{
for(int j=0; j<=y; j++)
{
visited[i][j] = false;
}
}
cout << lcs(0, 0);
return 0;
}