字符串的最大公因子 - C++力扣1071题
题目链接:https://leetcode.com/problems/greatest-common-divisor-of-strings/description/
解题思路
这题其实挺容易的,看我的代码只有两行就知道了。主要还是思路要有,要把力扣提供提示以及的例子看懂。
我们知道对于字符串 s 和 t,只有在 s = t + ... + t(t 自身连接 1 次或多次)时,我们才认定 t 能除尽 s。所以我们不妨假设 s = n t,那么 s + t = (n + 1) t,所以我们可以知道 s + t = t + s 的情况下,才能算是 t 能除尽 s。最后我们也可以通过求两个字符串长度的 gcd 来求出字符串的最大公因子。
完整代码:
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
if(str1 + str2 != str2 + str1) return "";
return str1.substr(0, gcd(str1.length(), str2.length()));
}
};
版权属于:我是苏云曦吖
本文链接:https://yuisblog.com/archives/225/
本站未注明转载的文章均为原创,并采用
CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!