有人可以检查一下我的代码,因为在某些情况下,在这段代码中输出是正确的但是当我尝试测试这个输入zzzazzazz时输出不是我所期望的。
npm i hammerjs
答案 0 :(得分:1)
您可以提供要检查的字符串作为此函数的参数:
function checkPalindrome($text) {
//Eliminate punctuation and spaces
$str = preg_replace('/[^a-z]+/i', '', $text);
// Force lower case
$str = strtolower($str);
//compare
$verdict = $str == strrev($str) ? '"' . $text . '" ' . 'is a palindrome' : '"' . $text . '"' . ' is not a palindrome';
return $verdict;
}
echo checkPalindrome("Red rum, sir, is murder");
请参见演示 here 。
答案 1 :(得分:0)
如果只有第一个字符匹配最后一个字符,则返回true - 您没有检查其余字符
$ ./check_2chars.sh
match
答案 2 :(得分:0)
你的代码到处都是。有很多方法可以解决这个问题,我不认为你甚至需要将字符串拆分成一个字符数组。但是,假设你想这样做,这是一个有效的实现:
repeat :all
基本思路是从两端开始沿着弦向下走,并逐一比较两侧的字符。如果我们发现两个字符不相同的情况,那么字符串不能是回文。请注意,这种方法涵盖了偶数和奇数长度的回文。在奇数长度回文的情况下,中心字符可以是任何东西,我写的循环甚至不会检查它。
答案 3 :(得分:0)
一种更简单的方法,使用strrev()并删除除a-z之外的所有字符然后小写。
<?php
function checkPalindrome($str) {
$str = strtolower(preg_replace('/[^a-z]+/i', '', $str));
return $str == strrev($str);
}
// test, few taken from http://www.palindromelist.net
$palindromes = [
'A but tuba.',
'madam',
'hannah',
'A dog, a plan, a canal: pagoda.',
'Nurses run',
'A dog! A panic in a pagoda!',
'A lad named E. Mandala',
'A man, a plan, a canal: Panama.',
'A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!',
'A new order began, a more Roman age bred Rowena.',
'Decaf and DNA faced.',
'Dennis and Edna sinned.',
'Devil never even lived.',
'Dr. Awkward',
'On a clover, if alive, erupts a vast, pure evil; a fire volcano.',
'See, slave, I demonstrate yet arts no medieval sees.',
'Star? Come, Donna Melba, I’m an amiable man – no Democrats!',
'Swap God for a janitor; rot in a jar of dog paws.',
];
foreach ($palindromes as $str) {
echo $str.(checkPalindrome($str) ? ' is' : 'is not').' a palindrome'.PHP_EOL;
}
<强>结果:强>
A but tuba. is a palindrome
madam is a palindrome
hannah is a palindrome
A dog, a plan, a canal: pagoda. is a palindrome
Nurses run is a palindrome
A dog! A panic in a pagoda! is a palindrome
A lad named E. Mandala is a palindrome
A man, a plan, a canal: Panama. is a palindrome
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama! is a palindrome
A new order began, a more Roman age bred Rowena. is a palindrome
Decaf and DNA faced. is a palindrome
Dennis and Edna sinned. is a palindrome
Devil never even lived. is a palindrome
Dr. Awkward is a palindrome
On a clover, if alive, erupts a vast, pure evil; a fire volcano. is a palindrome
See, slave, I demonstrate yet arts no medieval sees. is a palindrome
Star? Come, Donna Melba, I’m an amiable man – no Democrats! is a palindrome
Swap God for a janitor; rot in a jar of dog paws. is a palindrome