[Algorithm] Longest Common Substring (C++/DP/Medium)

Changjin
Feb 17, 2021

--

Problem Link: https://binarysearch.com/problems/Longest-Common-Substring

Hello! Today we’ll be looking at another typical dynamic programming problem: Longest Common Substring. Notice that this is different from “Longest Common Subsequence”. A substring is a contiguous chunk of subarray while a subsequence is a subarray whose elements need not be adjacent to each other.

Longest Common Substring can be solved with a slight variation of the Longest Common Subsequence.

Let dp[i][j] = The length of the longest common substring ending at [i,j].

There are TWO important intuitions to form a recurrence relation

  1. If s[i]!=t[j], then dp[i][j]=0 (definition of dp[i][j])
  2. If s[i]==t[j], then dp[i][j] = dp[i-1][j-1] + 1

Code

Time Complexity: O(n*m)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Changjin
Changjin

No responses yet

Write a response