-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalindromic.cpp
More file actions
59 lines (52 loc) · 1.39 KB
/
Copy pathpalindromic.cpp
File metadata and controls
59 lines (52 loc) · 1.39 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
/*
--- Longest Palindromic Substring ---
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
*/
#include <iostream>
#include <string>
#include <algorithm>
using std::cout;
using std::string;
int main()
{
string s;
std::getline(std::cin, s); // for testing only XXXXXXXXX
int n = s.size();
int greatest_len = 0;
string longest_pal = "";
// case 1: middle "mid" is a char
for(int mid = 0; mid < n; mid++) {
for(int x = 0; mid - x >= 0 && mid + x < n; x++) {
if(s[mid-x] != s[mid+x]) {
break;
}
int len = 2 * x + 1;
if(len > greatest_len) {
greatest_len = len;
longest_pal = s.substr(mid - x, len);
}
}
}
// case 2: middle "mid" is between two chars
for(int mid = 0; mid < n - 1; mid++) {
for(int x = 1; mid - x + 1 >= 0 && mid + x < n; x++) {
if(s[mid-x+1] != s[mid+x]) {
break;
}
int len = 2 * x;
if(len > greatest_len) {
greatest_len = len;
longest_pal = s.substr(mid - x + 1, len);
}
}
}
cout << longest_pal << "\n";
}