Skip to content

Commit 2f48aef

Browse files
authored
Add brute force solution for longest palindromic substring
1 parent 462e4ea commit 2f48aef

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <iostream>
2+
#include <string>
3+
using namespace std;
4+
5+
// Function to check if a string is palindrome
6+
bool isPalindrome(string s) {
7+
int left = 0, right = s.length() - 1;
8+
while (left < right) {
9+
if (s[left] != s[right])
10+
return false;
11+
left++;
12+
right--;
13+
}
14+
return true;
15+
}
16+
17+
// Function to find longest palindromic substring (brute force)
18+
string longestPalindrome(string str) {
19+
int n = str.length();
20+
string longest = "";
21+
22+
for (int i = 0; i < n; i++) {
23+
for (int j = i; j < n; j++) {
24+
string sub = str.substr(i, j - i + 1);
25+
26+
if (isPalindrome(sub) && sub.length() > longest.length()) {
27+
longest = sub;
28+
}
29+
}
30+
}
31+
32+
return longest;
33+
}
34+
35+
int main() {
36+
string str;
37+
cout << "Enter string: ";
38+
cin >> str;
39+
40+
string result = longestPalindrome(str);
41+
cout << "Longest Palindromic Substring: " << result << endl;
42+
43+
return 0;
44+
}

0 commit comments

Comments
 (0)