Skip to content

Commit

Permalink
Create code2.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
cloudzfy committed Apr 29, 2016
1 parent 13dd96a commit 0016be9
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions 005.longest_palindromic_substring/code2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution {
public:
string longestPalindrome(string s) {
string exS = preProcess(s);
int n = exS.length();
vector<int> dp(n, 0);
int C = 0, R = 0;
for (int i = 1; i < n; i++) {
int j = 2 * C - i;
dp[i] = R > i ? min(R - i, dp[j]) : 0;
while (i - 1 - dp[i] >= 0 && i + 1 + dp[i] < n && exS[i - 1 - dp[i]] == exS[i + 1 + dp[i]]) dp[i]++;
if (R < i + dp[i]) {
R = i + dp[i];
C = i;
}
}
int len = 0, index = -1;
for (int i = 0; i < n; i++) {
if (dp[i] > len) {
len = dp[i];
index = i;
}
}
return s.substr((index - dp[index]) / 2, dp[index]);
}

string preProcess(string s) {
string ans;
ans.push_back('#');
for (int i = 0; i < s.length(); i++) {
ans.push_back(s[i]);
ans.push_back('#');
}
return ans;
}
};

0 comments on commit 0016be9

Please sign in to comment.