问题描述
For two strings s and t , we say "t divides s " if and only if s = 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 .
对于字符串s和t,当s=t+...+t(例如,t与自身连接一次或多次)时,可以说"t划分s"。
已知字符串str1和str2,返回可以划分str1和str2的最长字符串x。
举例
Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
str1="MJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJ"
str2="MJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJMJBUJ"
expected: MJBUJ
str1="ABABABAB"
str2="ABAB"
expected: ABAB
解决方法
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
return (str1 + str2 == str2 + str1)? str1.substr(0, __gcd(size(str1),size(str2))): "";
}
};
首先判断两个字符串相加后是否相等。
str1="ABCCAB", str2="AB"
str1 + str2 = "ABCCABAB"
str2 + str1 = "ABABCCAB"
∴不存在同时划分str1和str2的字符串
str1="ABAB", str2="AB"
str1 + str2 = "ABABAB"
str2 + str1 = "ABABAB"
∴存在同时划分str1和str2的字符串
如果存在,利用c++的gcd方法得到两个字符串长度的最大公约数,返回前最大公约数的字符串。
s=t+...+t,要意识到size(s) % size(t) = 0, 即s的长度可以被t的长度整除。由最长字符串联想到最大公约数。
最大公约数(Greatest common divisor)
由于直接调用gcd方法有些无聊。尝试写一下返回最大公约数的函数。
//递归写法
int my_gcd2(int a, int b, int divisor)
{
if(a % divisor == 0 && b % divisor == 0)
return divisor;
return my_gcd2(a, b, divisor-1);
}
int my_gcd(int a, int b)
{
int divisor = (a < b)? a: b;
return my_gcd2(a, b, divisor);
}
更精简的代码,出自这里。
int gcd(int n, int m) {
for (int i = m <= n ? m : n; i > 1; i--) { //顺带复习:<=的运算顺序是自右向左的
if (n % i == 0 && m % i == 0) return i;
}
}