解题思路:
(1)首先判断字符串B中是否含有字符串A,并判断含有几个A
(2)如果,B中仅有整数n个A,即为所求
(3)如果B中除了含有整数个A外还有首部多余的字符串,此时判断是否与A的尾部匹配,匹配返回n+1,否则返回-1
(4)如果B中除了含有整数个A外还有尾部多余的字符串,此时判断是否与A的首部匹配,匹配返回n+1,否则返回-1
(5)如果B中除了含有整数个A外还有首尾部多余的字符串,此时按照(3)和(4)处理,同时满足返回n+2,否则返回-1
(6)如果,B中不含有A,判断(A+A)是否包含B,是返回2,否则返回-1
class Solution {
public:
int repeatedStringMatch(string A, string B) {
if (A.length()>B.length()) {
if (A.find(B)!=string::npos) {
return 1;
} else {
if ((A+A).find(B)!=string::npos) return 2;
else return -1;
}
}
int index_i = 0,index_j = 0;
int count = 0;
string s = "";
index_i = B.find(A); //第一次出现的位置
index_j = B.rfind(A); //最后一次出现的位置
if (index_i!=string::npos) {
if ((index_j-index_i)%A.length()!=0) {
index_i = index_i + A.length() - 1;
}
count = (index_j-index_i)/A.length()+1;
for (int i=0;i<count;i++) { //构建A的重复字符串
s+=A;
}
if (s==B.substr(index_i,count*A.length())) {
if (index_i == 0 && index_j+A.length()==B.length()) { //B正好是A整数倍
return count;
} else {
if (index_i > 0 && index_j+A.length()==B.length()) { //首部有多余
if(judge(A,B.substr(0,index_i),0)) return count+1; //B首部多余部分在A中
else return -1;
} else {
if (index_i == 0 && index_j+A.length() < B.length()) { //尾部有多余
if (judge(A,B.substr(index_j+A.length(),B.length()-index_j-A.length()),1)) return count+1; //B尾部多余部分在A中
else return -1;
} else { //B首尾都有多余
if (judge(A,B.substr(0,index_i),0) && judge(A,B.substr(index_j+A.length(),B.length()-index_j-A.length()),1)) {
return count+2;
} else return -1;
}
}
}
} else {
return -1;
}
} else { //B的中间没有A的重复部分,若是真,只能在两倍A的子串中
if ((A+A).find(B)!=string::npos) return 2;
else return -1;
}
}
bool judge(string a,string b,int tag=0) { //比较从给定位置起 是否相同
if (a.length()<b.length()) return false;
if (tag==0) {
int j = a.length()-1;
int i = b.length()-1;
while(i>=0 && j>=0) {
if (a[j]!=b[i]) {
return false;
} else {
i--;
j--;
}
}
return true;
} else {
int j = 0;
int i = 0;
while(i<b.length() && j<a.length()) {
if (a[j]!=b[i]) {
return false;
} else {
i++;
j++;
}
}
return true;
}
}
};