鏈接:https://leetcode-cn.com/problems/repeated-string-match
給定兩個字符串 A 和 B, 尋找重複疊加字符串A的最小次數,使得字符串B成爲疊加後的字符串A的子串,如果不存在則返回 -1。
舉個例子,A = “abcd”,B = “cdabcdab”。
答案爲 3, 因爲 A 重複疊加三遍後爲 “abcdabcdabcd”,此時 B 是其子串;A 重複疊加兩遍後爲"abcdabcd",B 並不是其子串。
注意:
A 與 B 字符串的長度在1和10000區間範圍內。
/* 思路
* A 的長度比B的長度大, 判斷B是否爲A的子串
* A 的長度小與B, A 擴展最小N倍自身長度,判斷B是否爲A的字串
*/
int BinA_string(char *A, char *B){
int i = 0;
int lena = strlen(A);
int lenb = strlen(B);
while(lena - i >= lenb){ // 判斷字符串B是否在字符串A中
if(*A == *B){
if(0 == strncmp(A, B, lenb)){
return 0;
}
}
A++;
i++;
}
return -1;
}
char* repeatA(char *A, int repeat_times){
char *newa = (char *)calloc(sizeof(char) * strlen(A) * repeat_times + 1, 1); // 要用calloc, 如果用malloc, 要memeset
while(repeat_times-- > 1){
strcat(newa, A); // 重複疊加,注意使用strcat
}
return newa;
}
int repeatedStringMatch(char * A, char * B){
int i = strlen(B) / strlen(A);
int j = 1;
char *newa = NULL;
for(j = 1; j <= 3; j++){ // A字符在不足B字符長度的情況下,先擴展N遍達到B字符的長度,然後最多擴展3次,如果還不包含就不會包含了
newa = repeatA(A, i + j);
if(0 == BinA_string(newa, B)){
return i + j - 1; // 注意次數
}
}
return -1;
}