forked from fineanmol/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest Palindromic Substring code
More file actions
51 lines (41 loc) · 1.25 KB
/
Longest Palindromic Substring code
File metadata and controls
51 lines (41 loc) · 1.25 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
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
if (s.empty()) return "";
int start = 0, maxLength = 1;
for (int i = 0; i < s.size(); i++) {
// Odd length palindrome
int len1 = expandAroundCenter(s, i, i);
// Even length palindrome
int len2 = expandAroundCenter(s, i, i + 1);
int len = max(len1, len2);
if (len > maxLength) {
start = i - (len - 1) / 2;
maxLength = len;
}
}
return s.substr(start, maxLength);
}
private:
// Helper function to expand around the center
int expandAroundCenter(const string& s, int left, int right) {
while (left >= 0 && right < s.size() && s[left] == s[right]) {
left--;
right++;
}
// Return length of the palindrome
return right - left - 1;
}
};
int main() {
Solution solution;
string s;
cout << "Enter the string: ";
cin >> s;
string longestPalindromicSubstring = solution.longestPalindrome(s);
cout << "The longest palindromic substring is: " << longestPalindromicSubstring << endl;
return 0;
}