Given string str, How do you find the longest palindromic substring in str in MATLAB

MATLAB
x
22
function [longest_palindrome] = longest_palindrome(str)
% Initialize the longest palindrome to be the first character.
longest_palindrome = str(1);
% Loop through each character in the input string.
for i = 1:length(str)
% Find all odd length and even length palindromes with str(i) as mid point.
for j = 0:1
left = i; right = i + j;
while left >= 1 && right <= length(str) && strcmp(str(left), str(right)) == 1
if right - left + 1 > length(longest_palindrome)
longest_palindrome = str((left):(right));
end
left = left - 1; % Expand around center.
right = right + 1; % Expand around center.
end
end
🤖 Code Explanation
end
The code finds the longest palindrome in a given string. A palindrome is a word, phrase, or sequence that reads the same backwards as forwards.

More problems solved in MATLAB



















