Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the given string is palindrome? [closed]

People also ask

How do you verify a palindrome?

A simple method for this problem is to first reverse digits of num, then compare the reverse of num with num. If both are same, then return true, else false.

How do you find the string of a palindrome in a string?

Algorithm to check whether a string is a palindrome or not Input the string. Find the reverse of the string. If the reverse of the string is equal to the input string, then return true. Else, return false.

What is the algorithm for palindrome?

Algorithm to check whether a number is a palindrome or notInput the number. Find the reverse of the number. If the reverse of the number is equal to the number, then return true. Else, return false.


PHP sample:

$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.


Windows XP (might also work on 2000) or later BATCH script:

@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

Language agnostic meta-code then...

rev = StringReverse(originalString)
return ( rev == originalString );

C# in-place algorithm. Any preprocessing, like case insensitivity or stripping of whitespace and punctuation should be done before passing to this function.

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!


C#: LINQ

var str = "a b a";
var test = Enumerable.SequenceEqual(str.ToCharArray(), 
           str.ToCharArray().Reverse());

A more Ruby-style rewrite of Hal's Ruby version:

class String
  def palindrome?
    (test = gsub(/[^A-Za-z]/, '').downcase) == test.reverse
  end
end

Now you can call palindrome? on any string.


Unoptimized Python:

>>> def is_palindrome(s):
...     return s == s[::-1]