日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

字符串中连续出现最多的子串 amp; 字符串中最长反复子串

發布時間:2025/7/14 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 字符串中连续出现最多的子串 amp; 字符串中最长反复子串 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.


字符串中連續出現最多的子串 & 字符串中最長反復子串

? ? 字符串中連續出現最多的子串 & 字符串中最長反復子串,這兩個問題都能夠用后綴數組來表示,至于后綴數組能夠參考編程珠璣P156;后綴數組就是定義一個數組指針,分別指向字符串中的相應位置,例如以下:

a b c?a b c a b c d e .substr[0]

b c a b c a b c d e ....substr[1]

c a b c a b c d e .......substr[2]

a b c?a b c d e ..........substr[3]

b c?a b c d e .............substr[4]

c a b c d e ...............substr[5]

a b c d e .................substr[6]

b c d e ...................substr[7]

c d e .....................substr[8]

d e ........................substr[9]

e ..........................substr[10]

上面的 substr 就是abcabcabcde的后綴數組;

一、字符串中連續出現最多的子串

針對這個問題能夠使用后綴數組的思想,能夠看到,子串連續出現,則滿足 substr[0].substr(i, j - i) = substr[j].substr(0, j - i)。知道了這一點程序就好編寫了,下面是C++代碼: <span style="font-size:18px;">string MaxTimesOfContinue(string str) {int len = str.length();int maxCount = 0;string longest = "";for (int i = 0; i < len; ++i){for (int j = i + 1; j < len; ++j){if (str.substr(i, j - i) == str.substr(j, j - i)){int offset = j - i;int count = 2;for (int k = j + offset; j <= len; k += offset){if (str.substr(i, offset) == str.substr(k, offset))++count;elsebreak;}if (count > maxCount){maxCount = count;longest = str.substr(i, offset);}}}}return longest; }</span>

二、字符串中最長反復子串

? ?這個問題相同能夠用后綴數組的思想來做,當然開始肯定想到的是暴力法,即求全部反復子串的長度,之后選擇一個最長的就可以。

int Comlen(char *str1, char *str2) {int i = 0;while(*str2 && (*str1++ == *str2++))++i;return i; }int MaxLength(char *str) {if(str == NULL)return 0;int maxLen = 0;int n = strlen(str);int maxi, maxj;for (int i = 0; i < n; ++i){for(int j = i + 1; j < n; ++j){int thisLen = 0;if ((thisLen = Comlen(&str[i], &str[j])) > maxLen){maxLen = thisLen;maxi = i;maxj = j;}}}return maxLen; }
若是使用后綴數組的方法能夠: 對于字符串 banana,其后綴數組為 a[0]:banana
a[1]:anana
a[2]:nana
a[3]:ana
a[4]:na
a[5]:a

將后綴數組按字典排序

a[0]:a
a[1]:ana
a[2]:anana
a[3]:banana?
a[4]:na
a[5]:nana

之后比較相鄰兩個子串就可以:

int Comlen(char *str1, char *str2) {int i = 0;while(*str2 && (*str1++ == *str2++))++i;return i; } int Pstrcmp(const void *a, const void *b) {return strcmp(*(char**)a, *(char**)b); } //char *a[11]; int MaxLength(char *str) {if(str == NULL)return 0;int maxLen = 0;int len = strlen(str);char **a = new char *[len + 1];for (int i = 0; i < len ; ++i)a[i] = &str[i];qsort(a, len , sizeof(char *), Pstrcmp);for (int i = 0; i < len - 1; ++i)if(Comlen(a[i], a[i+1]) > maxLen)maxLen = Comlen(a[i], a[i+1]);return maxLen; }


總結

以上是生活随笔為你收集整理的字符串中连续出现最多的子串 amp; 字符串中最长反复子串的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。