牛客網刷題(五) 尋找回文串(馬拉車演算法)
阿新 • • 發佈:2018-12-09
題目:設計一個演算法,尋找字串中的最長迴文子串。
輸入一行:一個字串
輸出兩行:最長迴文子串的長度(無則輸出0)
最長迴文子串(無則輸出空行)
思路:
一個迴文串它的對稱中心可能是某個字元(aba),也可能是某兩個字元之間(aa),理論上我們應該分類討論?但實際上我們這樣操作,我們把字串變成這樣(#a#b#)(#a#b#a#)
這樣一來,無論是什麼字串,它的長度都是奇數,只需要一種列舉方式就可以了(奇數的列舉方式,但同時可以列舉的偶數的情況)
#include<iostream> #include<vector> #include<stack> #include<string> using namespace std; int fun6(string str) { string tmp; int count = 0; int maxCount = 0; int j = 0; string::iterator it = str.begin(); while (it != str.end()) { tmp.insert(tmp.end(),'#'); tmp.insert(tmp.end(), *it); it++; } tmp.insert(tmp.end(), '#'); tmp.insert(tmp.end(), '\0'); cout << tmp << endl; for (int i = 1; i < tmp.size(); i++) { while (i - count - 1 >= 0 && i + count + 1 < tmp.size() && tmp[i - count - 1] == tmp[i + count + 1]) //列舉對稱軸,有對稱軸向左右兩邊列舉 { count++; } if (count > maxCount) { maxCount = count; j = i; } count = 0; } cout << j << endl; char *p = &(tmp[j - maxCount]); cout << p << endl; return maxCount; } int main() { string str = "qwqertre"; int maxCount = fun6(str); cout << maxCount << endl; return 0; }