-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy path5-longest-palindromic-substring.cpp
More file actions
113 lines (91 loc) · 2.95 KB
/
5-longest-palindromic-substring.cpp
File metadata and controls
113 lines (91 loc) · 2.95 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
Problem 5: Longest Palindromic Substring
https://leetcode.com/problems/longest-palindromic-substring/
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Constraints:
- 1 <= s.length <= 1000
- s consist of only digits and English letters.
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
// Approach 1: Expand Around Centers - O(n^2) time, O(1) space
string longestPalindrome(string s) {
if (s.empty()) return "";
int start = 0, maxLen = 1;
for (int i = 0; i < s.length(); i++) {
// Check for odd length palindromes (center at i)
int len1 = expandAroundCenter(s, i, i);
// Check for even length palindromes (center between i and i+1)
int len2 = expandAroundCenter(s, i, i + 1);
int len = max(len1, len2);
if (len > maxLen) {
maxLen = len;
start = i - (len - 1) / 2;
}
}
return s.substr(start, maxLen);
}
private:
int expandAroundCenter(const string& s, int left, int right) {
while (left >= 0 && right < s.length() && s[left] == s[right]) {
left--;
right++;
}
return right - left - 1;
}
public:
// Approach 2: Dynamic Programming - O(n^2) time, O(n^2) space
string longestPalindromeDP(string s) {
int n = s.length();
if (n == 0) return "";
vector<vector<bool>> dp(n, vector<bool>(n, false));
int start = 0, maxLen = 1;
// All single characters are palindromes
for (int i = 0; i < n; i++) {
dp[i][i] = true;
}
// Check for palindromes of length 2
for (int i = 0; i < n - 1; i++) {
if (s[i] == s[i + 1]) {
dp[i][i + 1] = true;
start = i;
maxLen = 2;
}
}
// Check for palindromes of length 3 and more
for (int len = 3; len <= n; len++) {
for (int i = 0; i < n - len + 1; i++) {
int j = i + len - 1;
if (s[i] == s[j] && dp[i + 1][j - 1]) {
dp[i][j] = true;
start = i;
maxLen = len;
}
}
}
return s.substr(start, maxLen);
}
};
// Test function
int main() {
Solution solution;
// Test cases
vector<string> testCases = {"babad", "cbbd", "a", "ac", "racecar"};
cout << "Testing Longest Palindromic Substring:\n";
for (const string& test : testCases) {
string result = solution.longestPalindrome(test);
cout << "Input: \"" << test << "\" -> Output: \"" << result << "\"\n";
}
return 0;
}