Find the length of longest common subsequence of two given strings.

Assumptions

  • The two given strings are not null

Examples

  • S = “abcde”, T = “cbabdfe”, the longest common subsequence of s and t is {‘a’, ‘b’, ‘d’, ‘e’}, the length is 4.

Solution: match[i][j]: s前i个字母和t前j个字母的longest common subsequence (maybe not including i and j)

s.charAt(i - 1) == t.charAt(j - 1)时,match[i][j] = match[i - 1][j - 1] + 1,否则match[i][j] = Math.max(match[i - 1][j], match[i][j - 1]);

  public int longest(String s, String t) {
    int[][] match = new int[s.length() + 1][t.length() + 1];
    for (int i = 1; i <= s.length(); i++) {
      for (int j = 1; j <= t.length(); j++) {
        if (s.charAt(i - 1) == t.charAt(j - 1)) {
          match[i][j] = match[i - 1][j - 1] + 1;
        } else {
          match[i][j] = Math.max(match[i - 1][j], match[i][j - 1]);
        }
      }
    }
    return match[s.length()][t.length()];
  }

results matching ""

    No results matching ""