给定一个大小为“n”的字符串。任务是从字符串移除或删除最少数量的字符,以便生成的字符串是回文。
注意:应该保持字符的顺序。
例子 :
Input : aebcbda
Output : 2
Remove characters 'e' and 'd'
Resultant string will be 'abcba'
which is a palindromic string
Input : geeksforgeeks
Output : 8
一个简单的解决方案是将所有子序列一个一个删除,然后检查剩余的字符串是否为回文。该解决方案的时间复杂度是指数级的。
一种有效的方法使用找到给定序列的最长回文子序列长度的概念。
算法:
1. str是给定的字符串。
2. str的n长度
3.len是最长的长度
str 的回文子序列
4. 最少删除次数
min = n – len
下面是上述方法的实现:
C++
// C++ implementation to find
// minimum number of deletions
// to make a string palindromic
#include
using namespace std;
// Returns the length of
// the longest palindromic
// subsequence in 'str'
int lps(string str)
{
int n = str.size();
// Create a table to store
// results of subproblems
int L[n][n];
// Strings of length 1
// are palindrome of length 1
for (int i = 0; i < n; i++)
L[i][i] = 1;
// Build the table. Note that
// the lower diagonal values
// of table are useless and
// not filled in the process.
// c1 is length of substring
for (int cl = 2; cl <= n; cl++)
{
for (int i = 0;
i < n - cl + 1; i++)
{
int j = i + cl - 1;
if (str[i] == str[j] &&
cl == 2)
L[i][j] = 2;
else if (str[i] == str[j])
L[i][j] = L[i + 1][j - 1] + 2;
else
L[i][j] = max(L[i][j - 1],
L[i + 1][j]);
}
}
// length of longest
// palindromic subseq
return L[0][n - 1];
}
// function to calculate
// minimum number of deletions
int minimumNumberOfDeletions(string str)
{
int n = str.size();
// Find longest palindromic
// subsequence
int len = lps(str);
// After removing characters
// other than the lps, we
// get palindrome.
return (n - len);
}
// Driver Code
int main()
{
string str = "geeksforgeeks";
cout << "Minimum number of deletions = "
<< minimumNumberOfDeletions(str);
return 0;
}
Java
// Java implementation to
// find minimum number of
// deletions to make a
// string palindromic
class GFG
{
// Returns the length of
// the longest palindromic
// subsequence in 'str'
static int lps(String str)
{
int n = str.length();
// Create a table to store
// results of subproblems
int L[][] = new int[n][n];
// Strings of length 1
// are palindrome of length 1
for (int i = 0; i < n; i++)
L[i][i] = 1;
// Build the table. Note
// that the lower diagonal
// values of table are useless
// and not filled in the process.
// c1 is length of substring
for (int cl = 2; cl <= n; cl++)
{
for (int i = 0; i < n - cl + 1; i++)
{
int j = i + cl - 1;
if (str.charAt(i) ==
str.charAt(j) && cl == 2)
L[i][j] = 2;
else if (str.charAt(i) ==
str.charAt(j))
L[i][j] = L[i + 1][j - 1] + 2;
else
L[i][j] = Integer.max(L[i][j - 1],
L[i + 1][j]);
}
}
// length of longest
// palindromic subsequence
return L[0][n - 1];
}
// function to calculate minimum
// number of deletions
static int minimumNumberOfDeletions(String str)
{
int n = str.length();
// Find longest palindromic
// subsequence
int len = lps(str);
// After removing characters
// other than the lps, we get
// palindrome.
return (n - len);
}
// Driver Code
public static void main(String[] args)
{
String str = "geeksforgeeks";
System.out.println("Minimum number " +
"of deletions = "+
minimumNumberOfDeletions(str));
}
}
// This code is contributed by Sumit Ghosh
Python3
# Python3 implementation to find
# minimum number of deletions
# to make a string palindromic
# Returns the length of
# the longest palindromic
# subsequence in 'str'
def lps(str):
n = len(str)
# Create a table to store
# results of subproblems
L = [[0 for x in range(n)]for y in range(n)]
# Strings of length 1
# are palindrome of length 1
for i in range(n):
L[i][i] = 1
# Build the table. Note that
# the lower diagonal values
# of table are useless and
# not filled in the process.
# c1 is length of substring
for cl in range( 2, n+1):
for i in range(n - cl + 1):
j = i + cl - 1
if (str[i] == str[j] and cl == 2):
L[i][j] = 2
elif (str[i] == str[j]):
L[i][j] = L[i + 1][j - 1] + 2
else:
L[i][j] = max(L[i][j - 1],L[i + 1][j])
# length of longest
# palindromic subseq
return L[0][n - 1]
# function to calculate
# minimum number of deletions
def minimumNumberOfDeletions( str):
n = len(str)
# Find longest palindromic
# subsequence
l = lps(str)
# After removing characters
# other than the lps, we
# get palindrome.
return (n - l)
# Driver Code
if __name__ == "__main__":
str = "geeksforgeeks"
print( "Minimum number of deletions = "
, minimumNumberOfDeletions(str))
C#
// C# implementation to find
// minimum number of deletions
// to make a string palindromic
using System;
class GFG
{
// Returns the length of
// the longest palindromic
// subsequence in 'str'
static int lps(String str)
{
int n = str.Length;
// Create a table to store
// results of subproblems
int [,]L = new int[n, n];
// Strings of length 1
// are palindrome of length 1
for (int i = 0; i < n; i++)
L[i, i] = 1;
// Build the table. Note
// that the lower diagonal
// values of table are useless
// and not filled in the process.
// c1 is length of substring
for (int cl = 2; cl <= n; cl++)
{
for (int i = 0; i < n - cl + 1; i++)
{
int j = i + cl - 1;
if (str[i] == str[j] && cl == 2)
L[i, j] = 2;
else if (str[i] == str[j])
L[i, j] = L[i + 1, j - 1] + 2;
else
L[i, j] = Math.Max(L[i, j - 1],
L[i + 1, j]);
}
}
// length of longest
// palindromic subsequence
return L[0, n - 1];
}
// function to calculate minimum
// number of deletions
static int minimumNumberOfDeletions(string str)
{
int n = str.Length;
// Find longest palindromic
// subsequence
int len = lps(str);
// After removing characters
// other than the lps, we get
// palindrome.
return (n - len);
}
// Driver Code
public static void Main()
{
string str = "geeksforgeeks";
Console.Write("Minimum number of" +
" deletions = " +
minimumNumberOfDeletions(str));
}
}
// This code is contributed by nitin mittal.
PHP
Javascript
C++
// C++ program for above approach
#include
using namespace std;
// Function to return minimum
// Element between two values
int min(int x, int y)
{
return (x < y) ? x : y;
}
// Utility function for calculating
// Minimum element to delete
int utility_fun_for_del(string str,
int i, int j)
{
if (i >= j)
return 0;
// Condition to compare characters
if (str[i] == str[j])
{
// Recursive function call
return utility_fun_for_del(str,
i + 1, j - 1);
}
// Return value, incrementing by 1
return 1 + min(utility_fun_for_del(str, i + 1, j),
utility_fun_for_del(str, i, j - 1));
}
// Function to calculate the minimum
// Element required to delete for
// Making string pelindrom
int min_ele_del(string str)
{
// Utility function call
return utility_fun_for_del(str, 0,
str.length() - 1);
}
// Driver code
int main()
{
string str = "abefbac";
cout << "Minimum element of deletions = "
<< min_ele_del(str) << endl;
return 0;
}
// This code is contributed by MOHAMMAD MUDASSIR
Java
// Java program for above approach
import java.io.*;
import java.util.*;
class GFG{
// Function to return minimum
// Element between two values
public static int min(int x, int y)
{
return (x < y) ? x : y;
}
// Utility function for calculating
// Minimum element to delete
public static int utility_fun_for_del(String str,
int i, int j)
{
if (i >= j)
return 0;
// Condition to compare characters
if (str.charAt(i) == str.charAt(j))
{
// Recursive function call
return utility_fun_for_del(str,
i + 1, j - 1);
}
// Return value, increamenting by 1
return 1 + Math.min(utility_fun_for_del(str, i + 1, j),
utility_fun_for_del(str, i, j - 1));
}
// Function to calculate the minimum
// Element required to delete for
// Making string pelindrom
public static int min_ele_del(String str)
{
// Utility function call
return utility_fun_for_del(str, 0,
str.length() - 1);
}
// Driver Code
public static void main(String[] args)
{
String str = "abefbac";
System.out.println("Minimum element of deletions = " +
min_ele_del(str));
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python3 program for above approach
# Utility function for calculating
# Minimum element to delete
def utility_fun_for_del(Str, i, j):
if (i >= j):
return 0
# Condition to compare characters
if (Str[i] == Str[j]):
# Recursive function call
return utility_fun_for_del(Str, i + 1,
j - 1)
# Return value, increamenting by 1
# return minimum Element between two values
return (1 + min(utility_fun_for_del(Str, i + 1, j),
utility_fun_for_del(Str, i, j - 1)))
# Function to calculate the minimum
# Element required to delete for
# Making string pelindrom
def min_ele_del(Str):
# Utility function call
return utility_fun_for_del(Str, 0,
len(Str) - 1)
# Driver code
Str = "abefbac"
print("Minimum element of deletions =",
min_ele_del(Str))
# This code is contributed by avanitrachhadiya2155
C#
// C# program for above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to return minimum
// Element between two values
static int min(int x, int y)
{
return (x < y) ? x : y;
}
// Utility function for calculating
// Minimum element to delete
static int utility_fun_for_del(string str,
int i, int j)
{
if (i >= j)
return 0;
// Condition to compare characters
if (str[i] == str[j])
{
// Recursive function call
return utility_fun_for_del(str, i + 1,
j - 1);
}
// Return value, increamenting by 1
return 1 + Math.Min(utility_fun_for_del(
str, i + 1, j),
utility_fun_for_del(
str, i, j - 1));
}
// Function to calculate the minimum
// Element required to delete for
// Making string pelindrom
static int min_ele_del(string str)
{
// Utility function call
return utility_fun_for_del(str, 0,
str.Length - 1);
}
// Driver code
static void Main()
{
string str = "abefbac";
Console.WriteLine("Minimum element of " +
"deletions = " +
min_ele_del(str));
}
}
// This code is contributed by divyesh072019
Javascript
C++
#include
using namespace std;
int dp[2000][2000];
// Function definition
int transformation(string s1, string s2,
int i, int j)
{
// Base cases
if (i >= (s1.size()) || j >= (s2.size()))
return 0;
// Checking the ndesired condition
if (s1[i] == s2[j])
{
// If yes increment the cunt
dp[i][j] = 1 + transformation(s1, s2, i + 1,
j + 1);
}
// If no
if (dp[i][j] != -1)
{
// Return the value form the table
return dp[i][j];
}
// Else store the max tranforamtion
// from the subsequence
else
dp[i][j] = max(transformation(s1, s2, i, j + i),
transformation(s1, s2, i + 1, j));
// Return the dp [-1][-1]
return dp[s1.size() - 1][s2.size() - 1];
}
// Driver code
int main()
{
string s1 = "geeksforgeeks";
string s2 = "geeks";
int i = 0;
int j = 0;
// Initialize the array with -1
memset(dp, -1, sizeof dp);
cout << "MINIMUM NUMBER OF DELETIONS: "
<< (s1.size()) - transformation(s1, s2, 0, 0)
<< endl;
cout << "MINIMUM NUMBER OF INSERTIONS: "
<< (s2.size()) - transformation(s1, s2, 0, 0)
<< endl;
cout << ("LCS LENGTH: ")
<< transformation(s1, s2, 0, 0);
}
// This code is contributed by Stream_Cipher
Java
import java.util.*;
public class GFG
{
static int dp[][] = new int[2000][2000];
// Function definition
public static int transformation(String s1,
String s2,
int i, int j)
{
// Base cases
if(i >= s1.length() || j >= s2.length())
{
return 0;
}
// Checking the ndesired condition
if(s1.charAt(i) == s2.charAt(j))
{
// If yes increment the cunt
dp[i][j] = 1 + transformation(s1, s2, i + 1, j + 1);
}
// If no
if(dp[i][j] != -1)
{
// Return the value form the table
return dp[i][j];
}
// Else store the max tranforamtion
// from the subsequence
else
{
dp[i][j] = Math.max(transformation(s1, s2, i, j + i),
transformation(s1, s2, i + 1, j));
}
// Return the dp [-1][-1]
return dp[s1.length() - 1][s2.length() - 1];
}
// Driver code
public static void main(String []args)
{
String s1 = "geeksforgeeks";
String s2 = "geeks";
int i = 0;
int j = 0;
// Initialize the array with -1
for (int[] row: dp)
{Arrays.fill(row, -1);}
System.out.println("MINIMUM NUMBER OF DELETIONS: " +
(s1.length() - transformation(s1, s2, 0, 0)));
System.out.println("MINIMUM NUMBER OF INSERTIONS: " +
(s2.length() - transformation(s1, s2, 0, 0)));
System.out.println("LCS LENGTH: " +
transformation(s1, s2, 0, 0));
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# function definition
def transformation(s1,s2,i,j,dp):
# base cases
if i>=len(s1) or j>=len(s2):
return 0
# checking the ndesired condition
if s1[i]==s2[j]:
# if yes increment the cunt
dp[i][j]=1+transformation(s1,s2,i+1,j+1,dp)
# if no
if dp[i][j]!=-1:
#return the value form the table
return dp[i][j]
# else store the max tranforamtion
# from the subsequence
else:
dp[i][j]=max(transformation(s1,s2,i,j+i,dp),
transformation(s1,s2,i+1,j,dp))
# return the dp [-1][-1]
return dp[-1][-1]
s1 = "geeksforgeeks"
s2 = "geeks"
i=0
j=0
#initialize the array with -1
dp=[[-1 for _ in range(len(s1)+1)] for _ in range(len(s2)+1)]
print("MINIMUM NUMBER OF DELETIONS: ",
len(s1)-transformation(s1,s2,0,0,dp),
end=" ")
print("MINIMUM NUMBER OF INSERTIONS: ",
len(s2)-transformation(s1,s2,0,0,dp),
end=" " )
print("LCS LENGTH: ",transformation(s1,s2,0,0,dp))
#code contributed by saikumar kudikala
C#
using System;
class GFG{
static int[,] dp = new int[2000, 2000];
// Function definition
static int transformation(string s1, string s2,
int i, int j )
{
// Base cases
if (i >= (s1.Length) || j >= (s2.Length))
{
return 0;
}
// Checking the ndesired condition
if (s1[i] == s2[j])
{
// If yes increment the cunt
dp[i, j] = 1 + transformation(s1, s2,
i + 1, j + 1);
}
// If no
if (dp[i, j] != -1)
{
// Return the value form the table
return dp[i, j];
}
// Else store the max tranforamtion
// from the subsequence
else
{
dp[i, j] = Math.Max(transformation(s1, s2, i,
j + i),
transformation(s1, s2,
i + 1, j));
}
// Return the dp [-1][-1]
return dp[s1.Length - 1, s2.Length - 1];
}
// Driver code
static public void Main()
{
string s1 = "geeksforgeeks";
string s2 = "geeks";
// Initialize the array with -1
for(int m = 0; m < 2000; m++ )
{
for(int n = 0; n < 2000; n++)
{
dp[m, n] = -1;
}
}
Console.WriteLine("MINIMUM NUMBER OF DELETIONS: " +
(s1.Length-transformation(s1, s2, 0, 0)));
Console.WriteLine("MINIMUM NUMBER OF INSERTIONS: " +
(s2.Length-transformation(s1, s2, 0, 0)));
Console.WriteLine("LCS LENGTH: " +
transformation(s1, s2, 0, 0));
}
}
// This code is contributed by rag2127
Javascript
输出
Minimum number of deletions = 8
时间复杂度: O(n 2 )
另一种方法:
- 将两个索引首先作为“i”,最后作为“j”
- 现在比较索引 ‘i’ 和 ‘j’ 处的字符
- 如果字符相等,则
- 通过将“i”递增“1”并将“j”递减“1”来递归调用该函数
- 别的
- 递归调用这两个函数,第一个将 ‘i’ 增加 ‘1’ 保持 ‘j’ 不变,第二个 ‘j’ 减少 ‘1’ 保持 ‘i’ 不变。
- 取两者的最小值并通过添加“1”返回
下面是上述方法的实现:
C++
// C++ program for above approach
#include
using namespace std;
// Function to return minimum
// Element between two values
int min(int x, int y)
{
return (x < y) ? x : y;
}
// Utility function for calculating
// Minimum element to delete
int utility_fun_for_del(string str,
int i, int j)
{
if (i >= j)
return 0;
// Condition to compare characters
if (str[i] == str[j])
{
// Recursive function call
return utility_fun_for_del(str,
i + 1, j - 1);
}
// Return value, incrementing by 1
return 1 + min(utility_fun_for_del(str, i + 1, j),
utility_fun_for_del(str, i, j - 1));
}
// Function to calculate the minimum
// Element required to delete for
// Making string pelindrom
int min_ele_del(string str)
{
// Utility function call
return utility_fun_for_del(str, 0,
str.length() - 1);
}
// Driver code
int main()
{
string str = "abefbac";
cout << "Minimum element of deletions = "
<< min_ele_del(str) << endl;
return 0;
}
// This code is contributed by MOHAMMAD MUDASSIR
Java
// Java program for above approach
import java.io.*;
import java.util.*;
class GFG{
// Function to return minimum
// Element between two values
public static int min(int x, int y)
{
return (x < y) ? x : y;
}
// Utility function for calculating
// Minimum element to delete
public static int utility_fun_for_del(String str,
int i, int j)
{
if (i >= j)
return 0;
// Condition to compare characters
if (str.charAt(i) == str.charAt(j))
{
// Recursive function call
return utility_fun_for_del(str,
i + 1, j - 1);
}
// Return value, increamenting by 1
return 1 + Math.min(utility_fun_for_del(str, i + 1, j),
utility_fun_for_del(str, i, j - 1));
}
// Function to calculate the minimum
// Element required to delete for
// Making string pelindrom
public static int min_ele_del(String str)
{
// Utility function call
return utility_fun_for_del(str, 0,
str.length() - 1);
}
// Driver Code
public static void main(String[] args)
{
String str = "abefbac";
System.out.println("Minimum element of deletions = " +
min_ele_del(str));
}
}
// This code is contributed by divyeshrabadiya07
蟒蛇3
# Python3 program for above approach
# Utility function for calculating
# Minimum element to delete
def utility_fun_for_del(Str, i, j):
if (i >= j):
return 0
# Condition to compare characters
if (Str[i] == Str[j]):
# Recursive function call
return utility_fun_for_del(Str, i + 1,
j - 1)
# Return value, increamenting by 1
# return minimum Element between two values
return (1 + min(utility_fun_for_del(Str, i + 1, j),
utility_fun_for_del(Str, i, j - 1)))
# Function to calculate the minimum
# Element required to delete for
# Making string pelindrom
def min_ele_del(Str):
# Utility function call
return utility_fun_for_del(Str, 0,
len(Str) - 1)
# Driver code
Str = "abefbac"
print("Minimum element of deletions =",
min_ele_del(Str))
# This code is contributed by avanitrachhadiya2155
C#
// C# program for above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to return minimum
// Element between two values
static int min(int x, int y)
{
return (x < y) ? x : y;
}
// Utility function for calculating
// Minimum element to delete
static int utility_fun_for_del(string str,
int i, int j)
{
if (i >= j)
return 0;
// Condition to compare characters
if (str[i] == str[j])
{
// Recursive function call
return utility_fun_for_del(str, i + 1,
j - 1);
}
// Return value, increamenting by 1
return 1 + Math.Min(utility_fun_for_del(
str, i + 1, j),
utility_fun_for_del(
str, i, j - 1));
}
// Function to calculate the minimum
// Element required to delete for
// Making string pelindrom
static int min_ele_del(string str)
{
// Utility function call
return utility_fun_for_del(str, 0,
str.Length - 1);
}
// Driver code
static void Main()
{
string str = "abefbac";
Console.WriteLine("Minimum element of " +
"deletions = " +
min_ele_del(str));
}
}
// This code is contributed by divyesh072019
Javascript
输出
Minimum element of deletions = 2
方法:自顶向下的动态规划
我们将首先定义 DP 表并在整个表中使用 -1 对其进行初始化。现在按照以下方法,
- 定义函数转换以计算将一个字符串转换为另一个字符串的最小删除和插入次数
- 我们写下基本情况的条件
- 检查通缉条件
- 如果满足条件,我们增加值并将值存储在表中
- 如果递归调用比我们直接利用表中的值更早解决
- 否则存储子序列的最大变换
- 我们将继续这个过程,直到我们达到基本条件
- 返回 DP [-1][-1]
下面是实现:
C++
#include
using namespace std;
int dp[2000][2000];
// Function definition
int transformation(string s1, string s2,
int i, int j)
{
// Base cases
if (i >= (s1.size()) || j >= (s2.size()))
return 0;
// Checking the ndesired condition
if (s1[i] == s2[j])
{
// If yes increment the cunt
dp[i][j] = 1 + transformation(s1, s2, i + 1,
j + 1);
}
// If no
if (dp[i][j] != -1)
{
// Return the value form the table
return dp[i][j];
}
// Else store the max tranforamtion
// from the subsequence
else
dp[i][j] = max(transformation(s1, s2, i, j + i),
transformation(s1, s2, i + 1, j));
// Return the dp [-1][-1]
return dp[s1.size() - 1][s2.size() - 1];
}
// Driver code
int main()
{
string s1 = "geeksforgeeks";
string s2 = "geeks";
int i = 0;
int j = 0;
// Initialize the array with -1
memset(dp, -1, sizeof dp);
cout << "MINIMUM NUMBER OF DELETIONS: "
<< (s1.size()) - transformation(s1, s2, 0, 0)
<< endl;
cout << "MINIMUM NUMBER OF INSERTIONS: "
<< (s2.size()) - transformation(s1, s2, 0, 0)
<< endl;
cout << ("LCS LENGTH: ")
<< transformation(s1, s2, 0, 0);
}
// This code is contributed by Stream_Cipher
Java
import java.util.*;
public class GFG
{
static int dp[][] = new int[2000][2000];
// Function definition
public static int transformation(String s1,
String s2,
int i, int j)
{
// Base cases
if(i >= s1.length() || j >= s2.length())
{
return 0;
}
// Checking the ndesired condition
if(s1.charAt(i) == s2.charAt(j))
{
// If yes increment the cunt
dp[i][j] = 1 + transformation(s1, s2, i + 1, j + 1);
}
// If no
if(dp[i][j] != -1)
{
// Return the value form the table
return dp[i][j];
}
// Else store the max tranforamtion
// from the subsequence
else
{
dp[i][j] = Math.max(transformation(s1, s2, i, j + i),
transformation(s1, s2, i + 1, j));
}
// Return the dp [-1][-1]
return dp[s1.length() - 1][s2.length() - 1];
}
// Driver code
public static void main(String []args)
{
String s1 = "geeksforgeeks";
String s2 = "geeks";
int i = 0;
int j = 0;
// Initialize the array with -1
for (int[] row: dp)
{Arrays.fill(row, -1);}
System.out.println("MINIMUM NUMBER OF DELETIONS: " +
(s1.length() - transformation(s1, s2, 0, 0)));
System.out.println("MINIMUM NUMBER OF INSERTIONS: " +
(s2.length() - transformation(s1, s2, 0, 0)));
System.out.println("LCS LENGTH: " +
transformation(s1, s2, 0, 0));
}
}
// This code is contributed by avanitrachhadiya2155
蟒蛇3
# function definition
def transformation(s1,s2,i,j,dp):
# base cases
if i>=len(s1) or j>=len(s2):
return 0
# checking the ndesired condition
if s1[i]==s2[j]:
# if yes increment the cunt
dp[i][j]=1+transformation(s1,s2,i+1,j+1,dp)
# if no
if dp[i][j]!=-1:
#return the value form the table
return dp[i][j]
# else store the max tranforamtion
# from the subsequence
else:
dp[i][j]=max(transformation(s1,s2,i,j+i,dp),
transformation(s1,s2,i+1,j,dp))
# return the dp [-1][-1]
return dp[-1][-1]
s1 = "geeksforgeeks"
s2 = "geeks"
i=0
j=0
#initialize the array with -1
dp=[[-1 for _ in range(len(s1)+1)] for _ in range(len(s2)+1)]
print("MINIMUM NUMBER OF DELETIONS: ",
len(s1)-transformation(s1,s2,0,0,dp),
end=" ")
print("MINIMUM NUMBER OF INSERTIONS: ",
len(s2)-transformation(s1,s2,0,0,dp),
end=" " )
print("LCS LENGTH: ",transformation(s1,s2,0,0,dp))
#code contributed by saikumar kudikala
C#
using System;
class GFG{
static int[,] dp = new int[2000, 2000];
// Function definition
static int transformation(string s1, string s2,
int i, int j )
{
// Base cases
if (i >= (s1.Length) || j >= (s2.Length))
{
return 0;
}
// Checking the ndesired condition
if (s1[i] == s2[j])
{
// If yes increment the cunt
dp[i, j] = 1 + transformation(s1, s2,
i + 1, j + 1);
}
// If no
if (dp[i, j] != -1)
{
// Return the value form the table
return dp[i, j];
}
// Else store the max tranforamtion
// from the subsequence
else
{
dp[i, j] = Math.Max(transformation(s1, s2, i,
j + i),
transformation(s1, s2,
i + 1, j));
}
// Return the dp [-1][-1]
return dp[s1.Length - 1, s2.Length - 1];
}
// Driver code
static public void Main()
{
string s1 = "geeksforgeeks";
string s2 = "geeks";
// Initialize the array with -1
for(int m = 0; m < 2000; m++ )
{
for(int n = 0; n < 2000; n++)
{
dp[m, n] = -1;
}
}
Console.WriteLine("MINIMUM NUMBER OF DELETIONS: " +
(s1.Length-transformation(s1, s2, 0, 0)));
Console.WriteLine("MINIMUM NUMBER OF INSERTIONS: " +
(s2.Length-transformation(s1, s2, 0, 0)));
Console.WriteLine("LCS LENGTH: " +
transformation(s1, s2, 0, 0));
}
}
// This code is contributed by rag2127
Javascript
输出:
MINIMUM NUMBER OF DELETIONS: 8 MINIMUM NUMBER OF INSERTIONS: 0 LCS LENGTH: 5
时间复杂度: O(N^K)
空间复杂度: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。