題目
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/greatest-common-divisor-of-strings
對(duì)于字符串 S 和 T,只有在 S = T + ... + T(T 與自身連接 1 次或多次)時(shí),我們才認(rèn)定 “T 能除盡 S”熙尉。
返回字符串 X,要求滿足 X 能除盡 str1 且 X 能除盡 str2窗轩。
示例 1:
輸入:str1 = "ABCABC", str2 = "ABC"
輸出:"ABC"
示例 2:
輸入:str1 = "ABABAB", str2 = "ABAB"
輸出:"AB"
示例 3:
輸入:str1 = "LEET", str2 = "CODE"
輸出:""
解法
func gcdOfStrings(str1 string, str2 string) string {
var result, shortOne string
string1 := str1 + str2
string2 := str2 + str1
if string1 != string2 {
return ""
}
strLen1 := len(str1)
strLen2 := len(str2)
var n int
if strLen1 > strLen2 {
n = strLen1
shortOne = str1
} else {
n = strLen2
shortOne = str2
}
var index int
for i := n; i >= 1; i-- {
if strLen1%i == 0 && strLen2%i == 0 {
index = i
break
}
}
result = string(shortOne[:index])
return result
}