keep learning, keep coding!
Problem - Greatest Common Divisor of Strings
For two strings s
and t
, we say “t
divides s
“ if and only if s = t + t + t + … + t + t (i.e., t
is concatenated with itself one or more times).
Given two strings str1
and str2
, return the largest string x such that x divides both str1
and str2
.
翻譯蒟蒻
一個字串 t
能整除另一個字串 s
時,意思是 s
可以由數個 t
串聯而成。
例如,如果 s
= “ababab” 並且 t
= “ab”,那麼我們可以說 t
能整除 s
,
因為 s
是由三個 t
串聯而成的 (t + t + t = “ab” + “ab” + “ab”)。
因此,給定兩個字符串 str1
和 str2
,目的是要找到一個最大字串 x
,
使得 x
能同時整除 str1
和 str2
。
Example 1:
1
2Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"Example 2:
1
2Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"Example 3:
1
2Input: str1 = "LEET", str2 = "CODE"
Output: ""
Solution - JavaScript
1 | var gcdOfStrings = function(str1, str2) { |
Solution - Ruby
1 | def gcd_of_strings(str1, str2) |
Solution - PHP
1 | function gcdOfStrings($str1, $str2) { |
Solution - Python3
1 | def gcdOfStrings(self, str1: str, str2: str) -> str: |