0% found this document useful (0 votes)
11 views2 pages

Agile A

Uploaded by

pranay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Agile A

Uploaded by

pranay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

how to compare two string and find common substring between them and substring length

should be greater than 1, print a list or array of the common substrings

ChatGPT said:

ChatGPT

To compare two strings and find common substrings with a length greater than 1, you can
use a dynamic programming approach. Here's how it can be done:

Python Example Code:

python

Copy code

def find_common_substrings(str1, str2):

# Initialize variables

len1, len2 = len(str1), len(str2)

dp = [[0] * (len2 + 1) for _ in range(len1 + 1)] # Create DP table

common_substrings = set() # To store common substrings

max_len = 0 # To track the longest common substring length

# Traverse through both strings

for i in range(1, len1 + 1):

for j in range(1, len2 + 1):

# If characters match, update the dp table

if str1[i - 1] == str2[j - 1]:

dp[i][j] = dp[i - 1][j - 1] + 1

# Add the substring if length > 1

if dp[i][j] > 1:

common_substrings.add(str1[i - dp[i][j]:i])

max_len = max(max_len, dp[i][j])


# Convert set to a sorted list for consistency

return sorted(common_substrings)

# Example usage

str1 = "abcdefg"

str2 = "zabcpqrsdef"

common_substrings = find_common_substrings(str1, str2)

print("Common substrings (length > 1):", common_substrings)

Explanation:

1. Dynamic Programming Table (dp):

o dp[i][j] stores the length of the common suffix between str1[0:i] and
str2[0:j].

o If the characters at position i-1 in str1 and j-1 in str2 match, then dp[i][j] =
dp[i-1][j-1] + 1.

2. Store Substrings:

o If the length of a common substring is greater than 1, it is added to the


common_substrings set.

o This ensures only substrings with a length greater than 1 are stored.

3. Output:

o The function returns a sorted list of common substrings.

Example Output:

For strings "abcdefg" and "zabcpqrsdef", the output will be:

You might also like