Longest Common Substring
Problem statement
Return a longest common substring of first and second. A substring is a consecutive block of characters; characters cannot be skipped inside the block. Return the string itself, rather than its length.
For this exercise, assume both inputs contain uppercase and lowercase English letters. Compare characters exactly and allow repeated letters.
For this exercise, assume equal maximum lengths choose the occurrence that starts earliest in first, then earliest in second. Return the empty string when either input is empty or there is no common character. Do not modify the inputs.
Function
longestCommonSubstring(first: String, second: String) → StringExamples
Example 1
first = "ababc"second = "babca"return = "babc"The shared consecutive string babc has length four. Return that string, rather than the number four.
Example 2
first = "xyABzzCD"second = "CDppAB"return = "AB"AB and CD both have length two. AB starts earlier in first, so choose AB.
Example 3
first = "axbxc"second = "abc"return = "a"The letters a, b and c cannot be joined across gaps. Each one-letter match is optimal; a starts earliest in first.
Constraints
- For this exercise, assume
0 <= first.length, second.length <= 500. - Every character is an uppercase or lowercase English letter; equality is case-sensitive.