字串相關模板

2021-07-23 06:53:02 字數 782 閱讀 8954

尋找字串s中字串t出現的位置或次數的問題屬於字串匹配問題

s的長度為n,t的長度為m。樸素方法,很容易想到,時間複雜度為o(nm).

下面介紹雜湊演算法

對於每個起始位置,我們不是o(m)直接比較字串是否匹配,而是o(l)的比較長度為m的字串的雜湊值與t的雜湊值是否相等。雖然雜湊值相等字串未必相等,但是若雜湊值隨機分布,不同字串雜湊值相等的概率很低,可以當做幾乎不會發生。

如果採用o(m)的演算法計算長度為m的字串子串的雜湊值,複雜度仍為o(nm)。這裡採用滾動雜湊的優化技巧。選取兩個合適的互素的常數h和b(l於是,不斷這樣計算開始位置右移移位後的字串子串的雜湊值。就可以在o(n)的時間內得到所有位置對應的雜湊值,從而可以在o(n+m)時間內完成字串匹配。在實現時,採用64位無符號整數計算雜湊值,並取h=2^64,通過自然溢位省去模運算。

#include #include #include #include #include #include #include #include #include #include #include #include #include #include#includeusing namespace std;

//字串匹配演算法模板

typedef unsigned long long ull;

const ull b=100000007;//雜湊的基數

//a是否在b中出現

bool contain(string a,string b)

return ans;

}

多行字串 模板字串

多行字串 下面是普通字串的寫法 普通字串 var l abcd console.log l 編譯結果 如何讓讓乙個字串獨佔多行呢?就需要用到es6 裡的多行字串 多行字串 var i ab cd console.log i 編譯結果 再說說拼接字串,一般情況我們是如何拼接字串的呢?看下面 正常拼接字...

模板 字串 字串匹配

計算next陣列的方法是對於長度為n的匹配串,從0到n 1位依次求出字首字尾最大匹配長度。下面的寫法是僅僅檢測有沒有匹配然後返回第乙個匹配位置,而不是返回所有匹配位置。include include include using namespace std const int n 100 char s...

字串模板

include include include include using namespace std const int maxn 1e6 7 int next maxn string s,t void get next string str void kmp intmain include in...