题目:
For strings S
and T
, we say "T
divides S
" if and only if S = T + ... + T
(T
concatenated with itself 1 or more times)
Return the largest string X
such that X
divides str1 and X
divides str2.
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: ""
Note:
1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i]
andstr2[i]
are English uppercase letters.
解题思路:
输入为str1和str2,定义:对于字符串T来说,若可以分解为字符串X的级联形式,如X X X ...,则称X为T的divisor分解串。输出时找到str1和str2的最大divisor并输出,若str1和str2不包含divisor则输出空字符串“”。
假设str2为较短的字串,先对它寻找divisor,然后将divisor与str1进行判断,如果不符合divisor条件则继续寻找,符合则返回输出。
代码:
class Solution {
public:
bool checkDivisor(string& T, string& X) {
if(T.length() % X.length())
return false;
int times = T.length() / X.length();
for(int i = 0; i<times; i++)
{
string subT = T.substr(i*X.length(), X.length());
if(subT != X)
return false;
}
return true;
}
string gcdOfStrings(string str1, string str2) {
if(str1.length() < 1 || str2.length() < 1)
return "";
if(str1.length() < str2.length())
{
swap(str1, str2);
}
string X = "";
for(int i = 1; i <= str2.length(); i++)
{
if(str2.length() % i)
continue;
string x = str2.substr(0, str2.length() / i);
if(!checkDivisor(str2, x))
continue;
if(checkDivisor(str1, x))
{
X = x;
break;
}
}
return X;
}
};
忘记string可以直接比较= =,也不太熟悉string的取子串substr接口,所以debug了一段时间。Anyway,最终还是AC啦~