string 如何检查给定的字符串是否为回文?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if the given string is palindrome?
提问by prakash
Definition:
定义:
A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction
回文是一个单词、短语、数字或其他单位序列,具有在任一方向阅读相同的属性
How to check if the given string is a palindrome?
如何检查给定的字符串是否是回文?
This was one of the FAIQ [Frequently Asked Interview Question] a while ago but that mostly using C.
这是不久前的 FAIQ [Frequently Asked Interview Question] 之一,但主要使用 C。
Looking for solutions in any and all languages possible.
寻找任何和所有可能的语言的解决方案。
回答by ConroyP
PHP sample:
PHP 示例:
$string = "A man, a plan, a canal, Panama";
function is_palindrome($string)
{
$a = strtolower(preg_replace("/[^A-Za-z0-9]/","",$string));
return $a==strrev($a);
}
Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words.
删除任何非字母数字字符(空格、逗号、感叹号等)以允许上述完整句子以及简单单词。
回答by Paulius
Windows XP (might also work on 2000) or later BATCH script:
Windows XP(可能也适用于 2000)或更高版本的 BATCH 脚本:
@echo off
call :is_palindrome %1
if %ERRORLEVEL% == 0 (
echo %1 is a palindrome
) else (
echo %1 is NOT a palindrome
)
exit /B 0
:is_palindrome
set word=%~1
set reverse=
call :reverse_chars "%word%"
set return=1
if "$%word%" == "$%reverse%" (
set return=0
)
exit /B %return%
:reverse_chars
set chars=%~1
set reverse=%chars:~0,1%%reverse%
set chars=%chars:~1%
if "$%chars%" == "$" (
exit /B 0
) else (
call :reverse_chars "%chars%"
)
exit /B 0
回答by Tnilsson
Language agnostic meta-code then...
语言不可知的元代码然后......
rev = StringReverse(originalString)
return ( rev == originalString );
回答by David Schmitt
C#in-place algorithm. Any preprocessing, like case insensitivity or stripping of whitespace and punctuation should be done before passing to this function.
C#就地算法。任何预处理,如不区分大小写或去除空格和标点符号,都应该在传递给这个函数之前完成。
boolean IsPalindrome(string s) {
for (int i = 0; i < s.Length / 2; i++)
{
if (s[i] != s[s.Length - 1 - i]) return false;
}
return true;
}
Edit:removed unnecessary "+1
" in loop condition and spent the saved comparison on removing the redundant Length comparison. Thanks to the commenters!
编辑:+1
在循环条件中删除了不必要的“ ”,并将保存的比较用于删除冗余的长度比较。感谢评论者!
回答by aku
C#: LINQ
C#:LINQ
var str = "a b a";
var test = Enumerable.SequenceEqual(str.ToCharArray(),
str.ToCharArray().Reverse());
回答by Brian Warshaw
A more Ruby-style rewrite of Hal's Ruby version:
对Hal 的 Ruby 版本进行更 Ruby 风格的重写:
class String
def palindrome?
(test = gsub(/[^A-Za-z]/, '').downcase) == test.reverse
end
end
Now you can call palindrome?
on any string.
现在您可以调用palindrome?
任何字符串。
回答by Jonathan
Java solution:
Java解决方案:
public class QuickTest {
public static void main(String[] args) {
check("AmanaplanacanalPanama".toLowerCase());
check("Hello World".toLowerCase());
}
public static void check(String aString) {
System.out.print(aString + ": ");
char[] chars = aString.toCharArray();
for (int i = 0, j = (chars.length - 1); i < (chars.length / 2); i++, j--) {
if (chars[i] != chars[j]) {
System.out.println("Not a palindrome!");
return;
}
}
System.out.println("Found a palindrome!");
}
}
}
回答by Blair Conrad
Unoptimized Python:
未优化的 Python:
>>> def is_palindrome(s):
... return s == s[::-1]
回答by xanadont
Using a good data structure usually helps impress the professor:
使用良好的数据结构通常有助于给教授留下深刻印象:
Push half the chars onto a stack (Length / 2).
Pop and compare each char until the first unmatch.
If the stack has zero elements: palindrome.
*in the case of a string with an odd Length, throw out the middle char.
将一半的字符压入堆栈(长度 / 2)。
弹出并比较每个字符,直到第一个不匹配。
如果堆栈有零个元素:回文。
*对于长度为奇数的字符串,丢弃中间的字符。
回答by Hostile
C in the house. (not sure if you didn't want a C example here)
C 在家里。(不确定您是否不想要这里的 C 示例)
bool IsPalindrome(char *s)
{
int i,d;
int length = strlen(s);
char cf, cb;
for(i=0, d=length-1 ; i < length && d >= 0 ; i++ , d--)
{
while(cf= toupper(s[i]), (cf < 'A' || cf >'Z') && i < length-1)i++;
while(cb= toupper(s[d]), (cb < 'A' || cb >'Z') && d > 0 )d--;
if(cf != cb && cf >= 'A' && cf <= 'Z' && cb >= 'A' && cb <='Z')
return false;
}
return true;
}
That will return true for "racecar", "Racecar", "race car", "racecar ", and "RaCe cAr". It would be easy to modify to include symbols or spaces as well, but I figure it's more useful to only count letters(and ignore case). This works for all palindromes I've found in the answers here, and I've been unable to trick it into false negatives/positives.
对于“racecar”、“Racecar”、“race car”、“racecar”和“RaCe car”,这将返回 true。修改以包含符号或空格也很容易,但我认为只计算字母(并忽略大小写)更有用。这适用于我在此处的答案中找到的所有回文,并且我无法将其欺骗为假阴性/阳性。
Also, if you don't like bool in a "C" program, it could obviously return int, with return 1 and return 0 for true and false respectively.
此外,如果您不喜欢“C”程序中的 bool,它显然可以返回 int,分别返回 1 和 0 分别表示真和假。