---
description: '# Medium'
---

# 1143. Longest Common Subsequence

{% hint style="success" %}
Very similar to #72, two-sequence DP problem

Subsequence: 子序列，可以跳着来

Substring: 子串，必须元素连续着
{% endhint %}

### Solution:

1. Initialize `maxCommon[i][j]`, which means longest common substring between `text1[:i]` and `text2[:j]`. Empty element is necessarily needed
2.  Three cases:

    1. `maxCommon[i-1][j]`. eg, `abc+d` and `ace`
    2. `maxCommon[i][j-1]`. eg, `abc` and `ac+d`
    3. If `text1[i] = text2[j]`, then `maxCommon[i][j] + 1` common char. eg, `abc+d` and `ace+d`

    Compare to assign biggest number to `maxCommon[i][j]`

![](https://3288217904-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LxJcc9A1TOyn5a5HJQ4%2F-MA4HJYiHMqprXzWaFHY%2F-MA4RC36obBt8sIWU69u%2F1592450385260.jpg?alt=media\&token=188456d0-cd83-4261-8902-7aefe967c6a5)

{% tabs %}
{% tab title="Python" %}
```python
class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        # initilize maxCommon
        maxCommon = [[-1]*(len(text2)+1) for i in range(len(text1)+1)]
        for i in range(len(text1)+1):
            maxCommon[i][0] = 0
        for j in range(len(text2)+1):
            maxCommon[0][j] = 0
            
        # compute
        for i in range(1, len(text1)+1):
            for j in range(1, len(text2)+1):
                maxCommon[i][j] = max(maxCommon[i-1][j], maxCommon[i][j-1])
                if text1[i-1] == text2[j-1]:
                    maxCommon[i][j] = max(maxCommon[i][j], maxCommon[i-1][j-1]+1)
                    
        return maxCommon[len(text1)][len(text2)]
```
{% endtab %}

{% tab title="Java" %}
```java
class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int[][] longest = new int[text1.length()+1][text2.length()+1];
        for(int i = 0; i <= text1.length(); i ++)
            Arrays.fill(longest[i], 0);
        
        for(int i = 1; i <= text1.length(); i ++)
            for(int j = 1; j <= text2.length(); j ++) {
                if(text1.charAt(i-1) == text2.charAt(j-1))
                    longest[i][j] = longest[i-1][j-1] + 1;
                else
                    longest[i][j] = Math.max(longest[i-1][j], longest[i][j-1]);
            }
        return longest[text1.length()][text2.length()];
    }
}
```
{% endtab %}
{% endtabs %}
