-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_214_ShortestPalindrome.cpp
62 lines (46 loc) · 1.14 KB
/
_214_ShortestPalindrome.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
/* Source - https://leetcode.com/problems/shortest-palindrome/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
string reverse (string s) {
int n = s.length();
for (int i = 0; i < n / 2; i++) {
char temp = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = temp;
}
return s;
}
int longestPrefixSuffix(string s) {
int i = 1, len = 0;
vector<int> lps(s.length());
lps[0] = 0;
while (i < s.length()) {
if (s[i] == s[len]) {
len++;
lps[i] = len;
i++;
}
else {
if (len > 0) len = lps[len - 1];
else {
lps[i] = 0;
i++;
}
}
}
return lps[s.length() - 1];
}
string shortestPalindrome(string s) {
string temp = s + "#" + reverse(s);
int p = longestPrefixSuffix(temp);
string rem = s.substr(p);
return reverse(rem) + s;
}
int main() {
string s;
cout<<"Enter string: ";
cin>>s;
cout<<"Shortest palindrome after minimum insertions: "<<shortestPalindrome(s)<<endl;
}