714129. Special Palindrome Substrings
Medium
Special Palindrome Substrings
Summary
Given a string, find all special palindrome substrings. A substring is considered special if it is a palindrome and its first and last characters are the same.
This problem involves manipulating strings to extract special palindromes. We'll use dynamic programming to solve this problem efficiently.
Detailed Explanation
To solve this problem, we'll follow these steps:
- Initialize an empty list
palindromesto store all special palindrome substrings. - Iterate through the string from left to right using a variable
i. - For each character at index
i, check if it's the same as the character at indexn-i-1. If they're not equal, skip this substring and move on to the next one. - While the characters at indices
iandn-i-1are equal, incrementiuntil they're no longer equal or we reach the middle of the string (wheni == n/2). - The substring from index
iton-i-1is a special palindrome. Add it to thepalindromeslist. - Return the
palindromeslist.
Here's an example: given the string "abccba", we'd find substrings like "b" and "abcba" (which is itself) as special palindromes.
Time complexity: O(n^2), where n is the length of the input string. We're doing a nested loop, iterating through the string twice.
Space complexity: O(n), as we need to store all special palindrome substrings in the palindromes list.
Optimized Solutions
Java
public List<String> findSpecialPalindromeSubstrings(String s) {
int n = s.length();
List<String> palindromes = new ArrayList<>();
for (int i = 0; i < n; i++) {
int left = i, right = n - i - 1;
while (left <= right && s.charAt(left) == s.charAt(right)) {
if (left == right) {
palindromes.add(String.valueOf(s.charAt(left)));
} else {
palindromes.add(s.substring(left, right + 1));
}
left++; right--;
}
}
return palindromes;
}