1. 程式人生 > 其它 >兩個字串的最大公共子竄

兩個字串的最大公共子竄

技術標籤:c/c++資料結構與演算法

const char* maxCommonString(char* str1, char* str2){
    //判斷非空性
    if(str1 == NULL || str2 == NULL){
        return NULL;
    }

    //計算兩個字串的大小,區分長短竄
    int iLen1 = strlen(str1);
    int iLen2 = strlen(str2);
    int iSmallLen = iLen1 > iLen2 ? iLen2 : iLen1;
    char* shortStr = iLen1 > iLen2 ? str2 : str1;
    char* longStr = iLen1 > iLen2 ? str1 : str2;

    //長竄是否包含短竄
    char* subStr = (char*)strStr((const char*)longStr, (const char*) shortStr);
    if(subStr != NULL)
        return subStr;//包含的話直接返回,完事

    //不包含,縮小子竄,繼續strStr 比較,得到的子竄放在堆記憶體中
     subStr = (char*)malloc(sizeof(char)*iSmallLen + 1);

     //開始尋找最大的包含的子竄,從長度為iSmallLen-1的子串開始
     for(int iLen = iSmallLen - 1; iLen > 0; iLen--){

         //從索引idex開始的,長度為iLen的子竄
         for(int idex = 0; idex <= iSmallLen - iLen; idex++){
             memcpy((void *)subStr, (const void*)shortStr + idex, iLen);
             subStr[iLen] = '\0';//末尾
            // puts("subStr: ");
            // puts(subStr);
             if(NULL != strStr((const char*)longStr, (const char*) subStr)){
                 return subStr;
             }
         }
     }
     return NULL;
}

int main(){
    char* p1 = "123456";
    char* p2 = "02304";
    const char* pstr = maxCommonString(p1, p2);
    puts("maxCommonString:");
    puts(pstr);
}