Skip to content

Commit 9536c1b

Browse files
MeetThakurpascalecu
authored andcommitted
Add Longest Palindromic Substring in C++ (TheRenegadeCoder#5096)
1 parent 0357f1e commit 9536c1b

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#include <iostream>
2+
#include <string>
3+
#include <cstring>
4+
5+
#define MAX_LENGTH 1000
6+
7+
int expandAroundCenter(const std::string& s, int left, int right) {
8+
while (left >= 0 && right < s.length() && s[left] == s[right]) {
9+
left--;
10+
right++;
11+
}
12+
return right - left - 1;
13+
}
14+
15+
bool longestPalindromicSubstring(const std::string& s, std::string& result) {
16+
if (s.empty()) {
17+
result = "";
18+
return false;
19+
}
20+
21+
int start = 0, maxLength = 0;
22+
int len = s.length();
23+
24+
for (int i = 0; i < len; i++) {
25+
int len1 = expandAroundCenter(s, i, i);
26+
int len2 = expandAroundCenter(s, i, i + 1);
27+
int len = (len1 > len2) ? len1 : len2;
28+
29+
if (len > maxLength) {
30+
start = i - (len - 1) / 2;
31+
maxLength = len;
32+
}
33+
}
34+
35+
if (maxLength > 1) {
36+
result = s.substr(start, maxLength);
37+
return true;
38+
}
39+
40+
result = "";
41+
return false;
42+
}
43+
44+
int main(int argc, char* argv[]) {
45+
if (argc != 2) {
46+
std::cout << "Usage: please provide a string that contains at least one palindrome" << std::endl;
47+
return 1;
48+
}
49+
50+
std::string input = argv[1];
51+
std::string result;
52+
53+
if (longestPalindromicSubstring(input, result) && !result.empty()) {
54+
std::cout << result << std::endl;
55+
} else {
56+
std::cout << "Usage: please provide a string that contains at least one palindrome" << std::endl;
57+
}
58+
59+
return 0;
60+
}

0 commit comments

Comments
 (0)