
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Greatest Common Divisor of Strings in Python
Suppose there are two strings A and B. We can say that A is divisible by B, when A is created by concatenating B one or more times. So if A = “abcabc”, and B = “abc”, then A is divisible by B. In this section, we will see what is the greatest common divisor of a String. So return the largest string that divides both of the strings. So if two strings are “ABABAB”, and “ABAB”, then GCD will be “AB”
To solve this, we will follow these steps −
- temp := shorter string between A and B
- m := length of temp
- x := 1
- res is an array and insert “” into the res
- while A and B has substring of size x, then add the substring into the res, and increase x by 1
- finally return the last element in the res array.
Example
Let us see the following implementation to get better understanding −
class Solution(object): def gcdOfStrings(self, str1, str2): if len(str1)<=len(str2): temp = str1 else: temp = str2 m = len(temp) x = 1 res=[""] while x<=m: if m%x==0 and temp[:x] * (len(str1)//x) == str1 and temp[:x] * (len(str2)//x) == str2: res.append(temp[:x]) x+=1 return res[-1] ob1 = Solution() print(ob1.gcdOfStrings("ABABAB","ABAB"))
Input
"ABABAB" "ABAB"
Output
AB
- Related Articles
- Return the greatest common divisor and lowest common multiple in Numpy
- Greatest common divisors in Python
- C++ Queries on XOR of Greatest Odd Divisor of the Range
- Common Words in Two Strings in Python
- Common words among tuple strings in Python
- Find the lowest common denominator or greatest common factor in Excel
- Program to find longest common prefix from list of strings in Python
- Python code to print common characters of two Strings in alphabetical order
- Program to find length of longest common subsequence of three strings in Python
- Program to find size of common special substrings of two given strings in Python
- Python program to remove words that are common in two Strings
- Python program to find better divisor of a number
- Common Character Count in Strings in JavaScript
- Python Program to Find the Smallest Divisor of an Integer
- Count common subsequence in two strings in C++

Advertisements