forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Shortest_Palindrome.cpp
121 lines (117 loc) · 3.37 KB
/
Shortest_Palindrome.cpp
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// using the idea of longest prefix suffix
// http://yucoding.blogspot.sg/2015/10/leetcode-question-shortest-palindrome.html
class Solution {
int computeLps(string s) {
vector<int>lps(s.length(), 0);
int len = 0;
int i = 1;
int n = s.length();
while(i < n) {
if(s[len] == s[i]) {
lps[i++] = ++len;
} else {
if(len > 0) {
len = lps[len - 1];
} else {
len = 0;
lps[i++] = len;
}
}
}
return lps[s.length() - 1];
}
public:
string shortestPalindrome(string s) {
if(s.length() <= 1) return s;
string reverseS = s.substr(0, s.length() - 1);
reverse(reverseS.begin(), reverseS.end());
int m = computeLps(s + reverseS);
if(m >= s.length()) {
return s;
}
string prefix = s.substr(m);
reverse(prefix.begin(), prefix.end());
return prefix + s;
}
};
// using longest palindrome substring
class Solution {
public:
string shortestPalindrome(string s) {
if(s.empty() or s.length() == 1) return s;
int n = s.length();
int maxLen = 0;
int left, right;
int len;
for(int i = 0; i < n; ++i) {
if(n - i >= i) {
left = i - 1;
right = i + 1;
while(left >= 0 and right < n and s[left] == s[right]) {
--left;
++right;
}
len = right - left - 1;
if(left < 0 and len > maxLen) {
maxLen = len;
}
}
if(n - i >= i + 1) {
left = i;
right = i + 1;
while(left >= 0 and right < n and s[left] == s[right]) {
--left;
++right;
}
len = right - left - 1;
if(left < 0 and len > maxLen) {
maxLen = len;
}
}
// early prune
if(n - i < i) {
break;
}
}
string result;
for(int i = n - 1; i >= maxLen; --i) {
result += s[i];
}
result.append(s);
return result;
}
};
// TLE
/*
class Solution {
bool isPalindrome(string& s, int left, int right) {
while(left < right) {
if(s[left++] != s[right--]) {
return false;
}
}
return true;
}
public:
string shortestPalindrome(string s) {
if(s.empty() or s.length() == 1) return s;
int n = s.length();
for(int left = 0, right = n - 1; left <= right; --right) {
if(s[left] == s[right]) {
if(isPalindrome(s, left + 1, right - 1)) {
// string prefix = s.substr(right + 1);
// reverse(prefix.begin(), prefix.end());
// string result = prefix + s;
string result;
result.reserve(n + n - right);
for(int k = n - 1; k > right; --k) {
result += s[k];
}
result += s;
return result;
}
}
}
}
};
*/