GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Algorithm/Manacher.cpp at master · stepByStepToSky/Algorithm Expand file tree/ Copy pathManacher.cppMore file actions 79 lines (68 loc) · 1.51 KB / Copy pathManacher.cppFile metadata and controls79 lines (68 loc) · 1.51 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; /* refrence https://zhuhongcheng.wordpress.com/2009/08/02/a-simple-linear-time-algorithm-for-finding-longest-palindrome-sub-string/ time complexity O(n) */ string LongestPalindrome(string s) { size_t n = s.size(); if (0 == n) { return s; } string str; str.reserve(2 * n + 1); str.push_back('#'); for (size_t i = 0; i < n; ++i) { str.push_back(s[i]); str.push_back('#'); } size_t strSize = str.size(); vector<int> vecLen(strSize, 1); int maxIndex = 0, maxRightIndex = 0; for (int i = 1; i < strSize; ++i) { int j = 2 * maxIndex - i; if (0 <= j && maxIndex + vecLen[j] <= maxRightIndex) { vecLen[i] = min(vecLen[j], maxRightIndex - i); } while (0 <= (i - vecLen[i]) && (i + vecLen[i]) < strSize && str[i - vecLen[i]] == str[i + vecLen[i]]) { ++vecLen[i]; } if (i + vecLen[i] >= maxRightIndex) { maxIndex = i; maxRightIndex = i + vecLen[i]; } } int maxLenIndex = 0; for (int i = 1; i < strSize; ++i) { if (vecLen[i] > vecLen[maxLenIndex]) { maxLenIndex = i; } } string ret; int orgMidIndex = maxLenIndex / 2, maxLen = vecLen[maxLenIndex] - 1; if (0x01 & maxLenIndex) { ret.assign(s.begin() + orgMidIndex - (maxLen / 2), s.begin() + orgMidIndex + (maxLen / 2) + 1); } else { ret.assign(s.begin() + orgMidIndex - (maxLen / 2), s.begin() + orgMidIndex + (maxLen / 2)); } return ret; } int main() { string s("babadada"); cout << LongestPalindrome(s) << endl; } |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |