求乙個字串中連續出現次數最多的子串

2021-04-17 02:03:27 字數 2875 閱讀 5237

求乙個字串中連續出現次數最多的子串,子串的長度可以是 1 。

乍一看,好像無處下手。簡單的窮舉效率太低,隨著輸入的文字增長,時間複雜度和空間複雜度就會火箭般竄公升至無法接受的地步。

我們需要尋找規律。

假設存在乙個長度為 n 的子串 s 出現的次數最多。那麼它具有哪些特點呢?

「s 中不會出現重複的字元」,「組成 s 的每乙個字元、每乙個子串的出現次數都和 s 一樣」!

有了這個結論,問題就簡單了。

找到文字中的出現次數最高的單個字元組成的子串,放入乙個佇列中,

從佇列的頭部開始,對結果集中的每乙個子串 s 進行處理

找到文字中該子串出現的任意乙個位置 p,

判斷文字中緊隨 s 之後的字元 c 是否的出現次數是最多的,

如果 c 的出現次數不是最多的,結束。

如果 c 的出現次數是最多的,搜尋文字中的每乙個 s 並判斷緊隨其後的字元是否是 c,

如果文字中的每乙個 s 之後都存在字元 c ,將 s + c 生成的子串放入結果集中,

如果文字中出現 s 之後的字元不是 c ,結束。

如此,直至到達佇列尾。

#pragma

warning(disable : 4786)

#include 

<

iostream

>

#include 

<

string

>

#include 

<

deque

>

#define

buffsize 1024

using

std::cout;

using

std::endl;

using

std::

string

;using

std::deque;

typedef deque

<

string

>

strlist;

const

string

::size_type npos =-

1;const

string

ignorechars(

"/t/n/r");

inline bool

ignorechar(

char

c)/*

* 統計字元出現次數

*/unsigned charsummary(

const

string

&text, unsigned usecount, 

inttbllen)

return

count;}/*

* 試著增長字串

*/char

trygrowthstring(

const

string

&text, 

const

string

&str, 

intmaxcount, unsigned

*usecount)

returnc;}

void

printresult(

const

strlist

&result)

cout

<<

"-------------------------------------

"<<

endl;

cout

<<

"total : 

"<<

result.size()

<<

endl;

}void

main(

void)/*

* 統計字元出現次數

*/count 

=charsummary(text, usecount, 

sizeof

(usecount) 

/sizeof(*

usecount));

cout

<<

"max count :

"<<

count

<<

endl;if(

0==count)

/** 將出現次數最多的字元作為子串放入結果中

*/for

(i =

0;i 

<

sizeof

(usecount) 

/sizeof(*

usecount);i++)

/** 查詢更多的子串

*/for

(strlist::iterator iter 

=result.begin();iter 

!=result.end();iter++)

printresult(result);

cout

<<

"bye!

"<<

endl;}

測試輸入:

abcdefg

bcdef

hijklmnopqrstabcdefg

輸出:

max count :3

the result substrings :

-------------------------------------""

"b""c"

"d""e"

"f""bc"

"cd"

"de"

"ef"

"bcd"

"cde"

"def"

"bcde"

"cdef"

"bcdef"

-------------------------------------

total : 16

bye!

字串問題 求乙個字串中連續出現次數最多的子串

2013 09 14 10 47 39 在面試寶典上看到的題目,自己做了一下,用了c 中的string類,比較方便。思路 遍歷源字串的每乙個字元,以該字元為首的重複子串的長度為1到以該字元為首的字尾字串 即以該字串為首,到字元結尾的子串,比如abdcef的第三個字尾字串即為dcef 的長度的一半 對...

字串問題 求乙個字串中連續出現次數最多的子串

2013 09 14 10 47 39 在面試寶典上看到的題目,自己做了一下,用了c 中的string類,比較方便。思路 遍歷源字串的每乙個字元,以該字元為首的重複子串的長度為1到以該字元為首的字尾字串 即以該字串為首,到字元結尾的子串,比如abdcef的第三個字尾字串即為dcef 的長度的一半 對...

求乙個字串中連續出現次數最多的子串

求乙個字串中連續出現次數最多的子串,例如 abcbcbcabc,這個串中連續出出次數最多的子串是bc,它出現了3次。以下是我的實現 用c語言實現,已經編譯通過。1 include 2 include 3 include 4 5 intcount 0 6charsub str 256 7 8 void...