Practical Code Examples
Real-World Palindrome Scenarios
1. Number Palindrome Validation
class NumberPalindrome {
public:
bool isPalindrome(int number) {
if (number < 0) return false;
long long reversed = 0;
int original = number;
while (number > 0) {
reversed = reversed * 10 + number % 10;
number /= 10;
}
return original == reversed;
}
};
2. String Palindrome with Advanced Filtering
class StringPalindrome {
public:
bool isPalindrome(string s) {
string filtered = filterString(s);
return checkPalindrome(filtered);
}
private:
string filterString(string& s) {
string result;
for (char c : s) {
if (isalnum(c)) {
result += tolower(c);
}
}
return result;
}
bool checkPalindrome(string& s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s[left++] != s[right--]) {
return false;
}
}
return true;
}
};
Palindrome Problem Categories
graph TD
A[Palindrome Problems] --> B[Number Palindromes]
A --> C[String Palindromes]
A --> D[Complex Palindromes]
B --> E[Integer Validation]
C --> F[Simple Matching]
C --> G[Advanced Filtering]
D --> H[Sentence Palindromes]
Technique |
Approach |
Time Complexity |
Space Complexity |
In-Place Checking |
Two Pointers |
O(n) |
O(1) |
Filtering Approach |
Preprocessing |
O(n) |
O(n) |
Recursive Method |
Recursive Comparison |
O(n) |
O(n) |
3. Longest Palindromic Substring
class LongestPalindrome {
public:
string longestPalindrome(string s) {
if (s.empty()) return "";
int start = 0, maxLength = 1;
for (int i = 0; i < s.length(); i++) {
// Odd length palindromes
int len1 = expandAroundCenter(s, i, i);
// Even length palindromes
int len2 = expandAroundCenter(s, i, i + 1);
int currentMax = max(len1, len2);
if (currentMax > maxLength) {
start = i - (currentMax - 1) / 2;
maxLength = currentMax;
}
}
return s.substr(start, maxLength);
}
private:
int expandAroundCenter(string& s, int left, int right) {
while (left >= 0 && right < s.length() && s[left] == s[right]) {
left--;
right++;
}
return right - left - 1;
}
};
Key Takeaways
- Understand different palindrome checking strategies
- Choose appropriate technique based on input type
- Consider time and space complexity
- Implement robust input validation
At LabEx, we emphasize practical problem-solving skills through comprehensive coding examples.