-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_005.cpp
More file actions
47 lines (36 loc) · 948 Bytes
/
Copy pathleetcode_005.cpp
File metadata and controls
47 lines (36 loc) · 948 Bytes
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
#include<iostream>
#include <string>
using namespace std;
string expandAroundCenter(const string& s, int left, int right) {
while (left >= 0 && right < s.size() && s[left] == s[right]) {
left--;
right++;
}
return s.substr(left + 1, right - left - 1);
}
string longestPalindrom(string s)
{
if (s.empty())
return "";
string result;
for (int i = 0; i < s.size(); i++) {
string oddLenPalindrome = expandAroundCenter(s, i, i);
string evenLenPalindrome = expandAroundCenter(s, i, i + 1);
if (oddLenPalindrome.length() > result.length()) {
result = oddLenPalindrome;
}
if (evenLenPalindrome.length() > result.length()) {
result = evenLenPalindrome;
}
}
return result;
}
int main(void)
{
string input;
cout << "Enter the string: ";
cin >> input;
string result = longestPalindrom(input);
cout << "Longest Palindromic Substring: " << result << endl;
return 0;
}