Home › Programming
#### Howdy, Stranger!

##
Quick Links

# Python code for longest common subsequence

#### I would appreciate any help that you can provide. Thank you!

It looks like you're new here. If you want to get involved, click one of these buttons!

Titan_S
Member

in Programming

I am looking for a Python code to find the longest common subsequence of two strings. I found a blog post on InterviewBit that describes the problem and provides a solution in Java. Can someone help me translate the Java code into Python?

The blog post can be found here: https://www.interviewbit.com/blog/longest-common-subsequence/

The Java code is as follows:

public int longestCommonSubsequence(String X, String Y) { int m = X.length(); int n = Y.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { dp[i][j] = 0; } else if (X.charAt(i - 1) == Y.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[m][n]; }