输出最大长度的回文子串。
1 string longestPalindrome(string s) 2 { 3 4 5 int id, mx, i, j, len, maxlen; 6 vector<char> cvec; 7 vector<int> ivec; 8 string str; 9 int ma, k; 10 11 id = 0; 12 mx = 0; 13 ivec.push_back(1); 14 len = s.size(); 15 maxlen = 2*s.size() + 1; 16 17 for (i = 0; i < len; ++i) 18 { 19 cvec.push_back(‘#‘); 20 cvec.push_back(s[i]); 21 } 22 cvec.push_back(‘#‘); 23 24 25 for (i = 1; i < maxlen; ++i) 26 { 27 if (mx > i) 28 { 29 int temp; 30 temp = ((mx - i - 1) > (ivec[2*id - i])) ? (ivec[2*id - i]) : (mx - i - 1); 31 ivec.push_back(temp); 32 } 33 else 34 ivec.push_back(1); 35 36 for (; (i - ivec[i] >= 0) && ((i + ivec[i]) < maxlen) && (cvec[i-ivec[i]] == cvec[i+ivec[i]]); ++ivec[i]) 37 ; 38 39 if (mx < ivec[i] + i -1 ) 40 { 41 mx = ivec[i] + i - 1; 42 id = i; 43 } 44 } 45 46 ma = 0; 47 for (i = 0; i < maxlen; ++i) 48 { 49 if (ivec[i] > ma) 50 { 51 ma = ivec[i]; 52 k = i; 53 } 54 } 55 56 for (j = 0, i = k - ivec[k] + 1; j < ivec[k] - 1; ++i, ++j) 57 { 58 ++i; 59 str.push_back(cvec[i]); 60 } 61 62 return str; 63 }
最大长度回文子串(Manacher's algorithm)
时间: 2024-10-10 06:36:46