xxxxxxxxxx
using System;
using System.Collections.Generic;
class Program
{
static int LcsUtil(string s1, string s2, int ind1, int ind2, List<List<int>> dp)
{
if (ind1 < 0 || ind2 < 0)
return 0;
if (dp[ind1][ind2] != -1)
return dp[ind1][ind2];
if (s1[ind1] == s2[ind2])
return dp[ind1][ind2] = 1 + LcsUtil(s1, s2, ind1 - 1, ind2 - 1, dp);
else
return dp[ind1][ind2] = Math.Max(LcsUtil(s1, s2, ind1, ind2 - 1, dp), LcsUtil(s1, s2, ind1 - 1, ind2, dp));
}
static int Lcs(string s1, string s2)
{
int n = s1.Length;
int m = s2.Length;
List<List<int>> dp = new List<List<int>>();
for (int i = 0; i < n; i++)
{
dp.Add(new List<int>());
for (int j = 0; j < m; j++)
{
dp[i].Add(-1);
}
}
return LcsUtil(s1, s2, n - 1, m - 1, dp);
}
static void Main(string[] args)
{
string s1 = "acd";
string s2 = "ced";
Console.WriteLine("The Length of Longest Common Subsequence is " + Lcs(s1, s2));
}
}
xxxxxxxxxx
#include <iostream>
#include <vector>
using namespace std;
string longestCommonSubsequence(string s1, string s2) {
int m = s1.length();
int n = s2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1[i - 1] == s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
// Backtrack to construct the LCS
int i = m, j = n;
string lcs;
while (i > 0 && j > 0) {
if (s1[i - 1] == s2[j - 1]) {
lcs = s1[i - 1] + lcs;
i--;
j--;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
i--;
} else {
j--;
}
}
return lcs;
}
int main() {
string s1, s2;
cout << "Enter the first string: ";
cin >> s1;
cout << "Enter the second string: ";
cin >> s2;
string result = longestCommonSubsequence(s1, s2);
cout << "Longest Common Subsequence: " << result << endl;
return 0;
}
xxxxxxxxxx
int findLength(vector<int>& nums1, vector<int>& nums2)
{
int n=nums1.size();
int m=nums2.size();
vector<vector<int>>dp(n+1,vector<int>(m+1));
for(int i=0;i<=n;i++)
{
dp[i][0]=0;
}
for(int i=0;i<=m;i++)
{
dp[0][i]=0;
}
int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(nums1[i-1]==nums2[j-1])
{
dp[i][j]=1+dp[i-1][j-1];
ans=max(ans,dp[i][j]);
}
else
{
dp[i][j]=0;
}
}
}
return ans;
}
xxxxxxxxxx
function func(line) {
let reg = /(\w)\1+/g;
let longest = line.match(reg).sort((a, b) => {
a.length - b.length
}).pop();
console.log(line + ' : ' + longest);
}
func('ddvvrwwwrggg');
func('sdsffffse');
func('abababaab');
func('aaabbcaaaa');
func('aaaasdfbbbbyyyweryyyuurweuuuuuu');
Run code snippet
xxxxxxxxxx
Copy
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if s == '':
return 0;
l = set();
m = 0;
i = 0;
j = 0;
while(i<len(s)):
if(s[i] not in l):
l.add(s[i])
i+=1
else:
m = max(m,len(l));
l.remove(s[j])
j+=1
m = max(m,len(l));
return m;