write a function called palindrome that takes one input argument a char vector and recursively determine whether that argument is a palindrome you are not allowed to use loops not built in function like srtcmp etc. the function returns true or false

7 次查看(过去 30 天)
function ok=palindrome(txt)
iflength(txt)<=1
ok=true;
else
ok=(txt(1)==txt(end)&&palindrome(txt(2:end-1)));
end
end
hi,
It shows error in else statment in the above program, kindly give me a solution to solve the above problem.

采纳的回答

Ameer Hamza
Ameer Hamza 2020-10-21
编辑:Ameer Hamza 2020-10-21
There should be a space between if keyword and the condition
if length(txt)<=1
%^ insert a space here
Apart from that, the logic is correct, but you just have a misplaced bracket. Following is correct
ok=(txt(1)==txt(end))&&palindrome(txt(2:end-1));

更多回答(3 个)

Sandeep Kumar Patel
编辑:DGM 2024-1-10
If we apply the edits recommended by @Ameer Hamza, we get this:
function ok=palindrome(txt)
if length(txt)<=1 % added space
ok = true;
else
ok = (txt(1)==txt(end)) && palindrome(txt(2:end-1));
% close parentheses --^
end
end

Black Woods
Black Woods 2022-12-12
function ans=palindrome(v)
if v(1)==v(end)
ans=true;
if length(v)==1 || length(v)==2
return
else
palindrome(v(2:length(v)-1));
end
else
ans=false;
end
end

Tarun Sangwan
Tarun Sangwan 2024-3-27
function p = palindrome(n)
if length(n)/2<1
p = 2
else
p = n(1) == n(end)
p = [p palindrome(n(2:end-1))]
end
p = ~ismember(0,p)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2014b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by