<p>I need to design a small project for generating excel reports in .NET, which will be sent to users to use.</p>

<p>The excel reports will contain PivotTables.</p>

<p>I don't have much experience with them, but I can think of three implementation alternatives:</p>

<ol>
<li>Set a query for it, populate it, send it disconnected. This way the user will be able to group values and play a little, but he will not be able to refresh the data.</li>
<li>Generate a small access database and send it along with the excel file, connect to it.</li>
<li>Copy the data to the excel (perhaps in some other sheet) and connect to the data there. This will make the excel file very large I think.</li>
</ol>

<p>What would be the best alternative in regards to performance vs usability? Is there another alternative I don't know about?</p>

[{'answer_id': 52013, 'author': 'Ryan Ahearn', 'author_id': 75, 'author_profile': 'https://Stackoverflow.com/users/75', 'pm_score': 2, 'selected': False, 'text': '<pre><code>boolean isPalindrome(String str1) {\n  //first strip out punctuation and spaces\n  String stripped = str1.replaceAll("[^a-zA-Z0-9]", "");\n  return stripped.equalsIgnoreCase((new StringBuilder(stripped)).reverse().toString());\n}\n</code></pre>\n\n<p>Java version</p>\n'}, {'answer_id': 52014, 'author': 'Tnilsson', 'author_id': 4165, 'author_profile': 'https://Stackoverflow.com/users/4165', 'pm_score': 5, 'selected': False, 'text': '<p>Language agnostic meta-code then...</p>\n\n<pre><code>rev = StringReverse(originalString)\nreturn ( rev == originalString );\n</code></pre>\n'}, {'answer_id': 52015, 'author': 'Jared', 'author_id': 1980, 'author_profile': 'https://Stackoverflow.com/users/1980', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s my solution in c#</p>\n\n<pre><code>static bool isPalindrome(string s)\n{\n    string allowedChars = "abcdefghijklmnopqrstuvwxyz"+\n        "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n    string compareString = String.Empty;\n    string rev = string.Empty;\n\n    for (int i = 0; i &lt;= s.Length - 1; i++)\n    {\n        char c = s[i];\n\n        if (allowedChars.IndexOf(c) &gt; -1)\n        {\n            compareString += c;\n        }\n    }\n\n\n    for (int i = compareString.Length - 1; i &gt;= 0; i--)\n    {\n        char c = compareString[i];\n        rev += c;\n    }\n\n    return rev.Equals(compareString, \n        StringComparison.CurrentCultureIgnoreCase);\n}\n</code></pre>\n'}, {'answer_id': 52021, 'author': 'gabr', 'author_id': 4997, 'author_profile': 'https://Stackoverflow.com/users/4997', 'pm_score': 3, 'selected': False, 'text': '<pre><code>Delphi\n\nfunction IsPalindrome(const s: string): boolean;\nvar\n  i, j: integer;\nbegin\n  Result := false;\n  j := Length(s);\n  for i := 1 to Length(s) div 2 do begin\n    if s[i] &lt;&gt; s[j] then\n      Exit;\n    Dec(j);\n  end;\n  Result := true;\nend;\n</code></pre>\n'}, {'answer_id': 52023, 'author': 'Blair Conrad', 'author_id': 1199, 'author_profile': 'https://Stackoverflow.com/users/1199', 'pm_score': 4, 'selected': False, 'text': '<p>Unoptimized Python:</p>\n\n<pre><code>&gt;&gt;&gt; def is_palindrome(s):\n...     return s == s[::-1]\n</code></pre>\n'}, {'answer_id': 52028, 'author': 'Baltimark', 'author_id': 1179, 'author_profile': 'https://Stackoverflow.com/users/1179', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s a python way. Note: this isn\'t really that "pythonic" but it demonstrates the algorithm.</p>\n\n<pre><code>def IsPalindromeString(n):\n    myLen = len(n)\n    i = 0\n    while i &lt;= myLen/2:\n        if n[i] != n[myLen-1-i]:\n            return False\n        i += 1\n    return True\n</code></pre>\n'}, {'answer_id': 52031, 'author': 'Paulius', 'author_id': 1353085, 'author_profile': 'https://Stackoverflow.com/users/1353085', 'pm_score': 5, 'selected': False, 'text': '<p>Windows XP (might also work on 2000) or later BATCH script:</p>\n\n<pre><code>@echo off\n\ncall :is_palindrome %1\nif %ERRORLEVEL% == 0 (\n    echo %1 is a palindrome\n) else (\n    echo %1 is NOT a palindrome\n)\nexit /B 0\n\n:is_palindrome\n    set word=%~1\n    set reverse=\n    call :reverse_chars "%word%"\n    set return=1\n    if "$%word%" == "$%reverse%" (\n        set return=0\n    )\nexit /B %return%\n\n:reverse_chars\n    set chars=%~1\n    set reverse=%chars:~0,1%%reverse%\n    set chars=%chars:~1%\n    if "$%chars%" == "$" (\n        exit /B 0\n    ) else (\n        call :reverse_chars "%chars%"\n    )\nexit /B 0\n</code></pre>\n'}, {'answer_id': 52034, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 4, 'selected': False, 'text': '<p>C#: LINQ</p>\n\n<pre><code>var str = "a b a";\nvar test = Enumerable.SequenceEqual(str.ToCharArray(), \n           str.ToCharArray().Reverse());\n</code></pre>\n'}, {'answer_id': 52036, 'author': 'Ryan Farley', 'author_id': 1627, 'author_profile': 'https://Stackoverflow.com/users/1627', 'pm_score': 1, 'selected': False, 'text': '<p>Many ways to do it. I guess the key is to do it in the most efficient way possible (without looping the string). I would do it as a char array which can be reversed easily (using C#).</p>\n\n<pre><code>string mystring = "abracadabra";\n\nchar[] str = mystring.ToCharArray();\nArray.Reverse(str);\nstring revstring = new string(str);\n\nif (mystring.equals(revstring))\n{\n    Console.WriteLine("String is a Palindrome");\n}\n</code></pre>\n'}, {'answer_id': 52038, 'author': 'David Schmitt', 'author_id': 4918, 'author_profile': 'https://Stackoverflow.com/users/4918', 'pm_score': 5, 'selected': False, 'text': '<p><strong>C#</strong> in-place algorithm. Any preprocessing, like case insensitivity or stripping of whitespace and punctuation should be done before passing to this function.</p>\n\n<pre><code>boolean IsPalindrome(string s) {\n    for (int i = 0; i &lt; s.Length / 2; i++)\n    {\n        if (s[i] != s[s.Length - 1 - i]) return false;\n    }\n    return true;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Edit:</strong> removed unnecessary "<code>+1</code>" in loop condition and spent the saved comparison on removing the redundant Length comparison. Thanks to the commenters!</p>\n'}, {'answer_id': 52039, 'author': 'xanadont', 'author_id': 1886, 'author_profile': 'https://Stackoverflow.com/users/1886', 'pm_score': 3, 'selected': False, 'text': '<p>Using a good data structure usually helps impress the professor:</p>\n\n<p>Push half the chars onto a stack (Length / 2).<br />\nPop and compare each char until the first unmatch.<br />\nIf the stack has zero elements: palindrome.<br />\n*in the case of a string with an odd Length, throw out the middle char.</p>\n'}, {'answer_id': 52040, 'author': 'swilliams', 'author_id': 736, 'author_profile': 'https://Stackoverflow.com/users/736', 'pm_score': 2, 'selected': False, 'text': "<p>Here's my solution, without using a strrev. Written in C#, but it will work in any language that has a string length function.</p>\n\n<pre><code>private static bool Pal(string s) {\n    for (int i = 0; i &lt; s.Length; i++) {\n        if (s[i] != s[s.Length - 1 - i]) {\n            return false;\n        }\n    }\n    return true;\n}\n</code></pre>\n"}, {'answer_id': 52041, 'author': 'Aaron', 'author_id': 2628, 'author_profile': 'https://Stackoverflow.com/users/2628', 'pm_score': 2, 'selected': False, 'text': '<p>This Java code should work inside a <strong>boolean</strong> method:</p>\n\n<p><strong>Note</strong>: You only need to check the first half of the characters with the back half, otherwise you are overlapping and doubling the amount of checks that need to be made.</p>\n\n<pre><code>private static boolean doPal(String test) {\n    for(int i = 0; i &lt; test.length() / 2; i++) {\n        if(test.charAt(i) != test.charAt(test.length() - 1 - i)) {\n            return false;\n        }\n    }\n    return true;\n}\n</code></pre>\n'}, {'answer_id': 52048, 'author': 'Jonathan', 'author_id': 1772, 'author_profile': 'https://Stackoverflow.com/users/1772', 'pm_score': 4, 'selected': False, 'text': '<p>Java solution:</p>\n\n<pre><code>public class QuickTest {\n\npublic static void main(String[] args) {\n    check("AmanaplanacanalPanama".toLowerCase());\n    check("Hello World".toLowerCase());\n}\n\npublic static void check(String aString) {\n    System.out.print(aString + ": ");\n    char[] chars = aString.toCharArray();\n    for (int i = 0, j = (chars.length - 1); i &lt; (chars.length / 2); i++, j--) {\n        if (chars[i] != chars[j]) {\n            System.out.println("Not a palindrome!");\n            return;\n        }\n    }\n    System.out.println("Found a palindrome!");\n}\n</code></pre>\n\n<p>}</p>\n'}, {'answer_id': 52051, 'author': 'ConroyP', 'author_id': 2287, 'author_profile': 'https://Stackoverflow.com/users/2287', 'pm_score': 6, 'selected': False, 'text': '<p><strong>PHP sample</strong>:</p>\n\n<pre><code>$string = "A man, a plan, a canal, Panama";\n\nfunction is_palindrome($string)\n{\n    $a = strtolower(preg_replace("/[^A-Za-z0-9]/","",$string));\n    return $a==strrev($a);\n}\n</code></pre>\n\n<p>Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words.</p>\n'}, {'answer_id': 52053, 'author': 'Flame', 'author_id': 5387, 'author_profile': 'https://Stackoverflow.com/users/5387', 'pm_score': 3, 'selected': False, 'text': '<p>EDIT: from the comments:</p>\n\n<pre><code>bool palindrome(std::string const&amp; s) \n{ \n  return std::equal(s.begin(), s.end(), s.rbegin()); \n} \n</code></pre>\n\n<hr>\n\n<p>The c++ way.</p>\n\n<p>My naive implementation using the elegant iterators. In reality, you would probably check\nand stop once your forward iterator has past the halfway mark to your string.</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n\nusing namespace std;\nbool palindrome(string foo)\n{\n    string::iterator front;\n    string::reverse_iterator back;\n    bool is_palindrome = true;\n    for(front = foo.begin(), back = foo.rbegin();\n        is_palindrome &amp;&amp; front!= foo.end() &amp;&amp; back != foo.rend();\n        ++front, ++back\n        )\n    {\n        if(*front != *back)\n            is_palindrome = false;\n    }\n    return is_palindrome;\n}\nint main()\n{\n    string a = "hi there", b = "laval";\n\n    cout &lt;&lt; "String a: \\"" &lt;&lt; a &lt;&lt; "\\" is " &lt;&lt; ((palindrome(a))? "" : "not ") &lt;&lt; "a palindrome." &lt;&lt;endl;\n    cout &lt;&lt; "String b: \\"" &lt;&lt; b &lt;&lt; "\\" is " &lt;&lt; ((palindrome(b))? "" : "not ") &lt;&lt; "a palindrome." &lt;&lt;endl;\n\n}\n</code></pre>\n'}, {'answer_id': 52057, 'author': 'JosephStyons', 'author_id': 672, 'author_profile': 'https://Stackoverflow.com/users/672', 'pm_score': 0, 'selected': False, 'text': "<p>Another one from Delphi, which I think is a little more rigorous than the other Delphi example submitted.  This can easily turn into a golfing match, but I've tried to make mine readable.</p>\n\n<p><em>Edit0: I was curious about the performance characteristics, so I did a little test.  On my machine, I ran this function against a 60 character string 50 million times, and it took 5 seconds.</em></p>\n\n<pre><code>function TForm1.IsPalindrome(txt: string): boolean;\nvar\n  i, halfway, len : integer;\nbegin\n  Result := True;\n  len := Length(txt);\n\n  {\n  special cases:\n  an empty string is *never* a palindrome\n  a 1-character string is *always* a palindrome\n  }\n  case len of\n    0 : Result := False;\n    1 : Result := True;\n    else begin\n      halfway := Round((len/2) - (1/2));  //if odd, round down to get 1/2way pt\n\n      //scan half of our string, make sure it is mirrored on the other half\n      for i := 1 to halfway do begin\n        if txt[i] &lt;&gt; txt[len-(i-1)] then begin\n          Result := False;\n          Break;\n        end;  //if we found a non-mirrored character\n      end;  //for 1st half of string\n    end;  //else not a special case\n  end;  //case\nend;\n</code></pre>\n\n<p>And here is the same thing, in C#, except that I've left it with multiple exit points, which I don't like.</p>\n\n<pre><code>private bool IsPalindrome(string txt) {\n  int len = txt.Length;\n\n  /*\n  Special cases:\n  An empty string is *never* a palindrome\n  A 1-character string is *always* a palindrome\n  */    \n  switch (len) {\n    case 0: return false;\n    case 1: return true;\n  }  //switch\n  int halfway = (len / 2);\n\n  //scan half of our string, make sure it is mirrored on the other half\n  for (int i = 0; i &lt; halfway; ++i) {\n    if (txt.Substring(i,1) != txt.Substring(len - i - 1,1)) {\n      return false;\n    }  //if\n  }  //for\n  return true;\n}\n</code></pre>\n"}, {'answer_id': 52063, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 0, 'selected': False, 'text': '<p>C#3 - This returns false as soon as a char counted from the beginning fails to match its equivalent at the end:</p>\n\n<pre><code>static bool IsPalindrome(this string input)\n{\n    char[] letters = input.ToUpper().ToCharArray();\n\n    int i = 0;\n    while( i &lt; letters.Length / 2 )\n        if( letters[i] != letters[letters.Length - ++i] )\n            return false;\n\n    return true;\n}\n</code></pre>\n'}, {'answer_id': 52064, 'author': 'David Webb', 'author_id': 3171, 'author_profile': 'https://Stackoverflow.com/users/3171', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s a Python version that deals with different cases, punctuation and whitespace.</p>\n\n<pre><code>import string\n\ndef is_palindrome(palindrome):\n    letters = palindrome.translate(string.maketrans("",""),\n                  string.whitespace + string.punctuation).lower()\n    return letters == letters[::-1]\n</code></pre>\n\n<p><strong>Edit:</strong> Shamelessly stole from <a href="https://stackoverflow.com/questions/52002/how-to-check-if-the-given-string-is-palindrome#52023">Blair Conrad\'s</a> neater answer to remove the slightly clumsy list processing from my previous version. </p>\n'}, {'answer_id': 52138, 'author': 'Sébastien RoccaSerra', 'author_id': 2797, 'author_profile': 'https://Stackoverflow.com/users/2797', 'pm_score': 2, 'selected': False, 'text': '<p>Three versions in Smalltalk, from dumbest to correct.</p>\n\n<hr>\n\n<p>In Smalltalk, <code>=</code> is the comparison operator:</p>\n\n<pre><code>isPalindrome: aString\n    "Dumbest."\n    ^ aString reverse = aString\n</code></pre>\n\n<hr>\n\n<p>The message <code>#translateToLowercase</code> returns the string as lowercase:</p>\n\n<pre><code>isPalindrome: aString\n    "Case insensitive"\n    |lowercase|\n    lowercase := aString translateToLowercase.\n    ^ lowercase reverse = lowercase\n</code></pre>\n\n<hr>\n\n<p>And in Smalltalk, strings are part of the <code>Collection</code> framework, you can use the message <code>#select:thenCollect:</code>, so here\'s the last version:</p>\n\n<pre><code>isPalindrome: aString\n    "Case insensitive and keeping only alphabetic chars\n    (blanks &amp; punctuation insensitive)."\n    |lowercaseLetters|\n    lowercaseLetters := aString\n        select: [:char | char isAlphabetic]\n        thenCollect: [:char | char asLowercase]. \n    ^ lowercaseLetters reverse = lowercaseLetters\n</code></pre>\n'}, {'answer_id': 52153, 'author': 'Leon Timmermans', 'author_id': 4727, 'author_profile': 'https://Stackoverflow.com/users/4727', 'pm_score': 2, 'selected': False, 'text': '<p>Another C++ one. Optimized for speed and size.</p>\n\n<p><code><pre>bool is_palindrome(const std::string&amp; candidate) {\n    for(std::string::const_iterator left = candidate.begin(), right = candidate.end(); left &lt; --right ; ++left)\n        if (*left != *right)\n            return false;\n    return true;\n}</pre></code></p>\n'}, {'answer_id': 52328, 'author': 'kranzky', 'author_id': 5442, 'author_profile': 'https://Stackoverflow.com/users/5442', 'pm_score': 1, 'selected': False, 'text': '<p>In Ruby, converting to lowercase and stripping everything not alphabetic:</p>\n\n<pre><code>def isPalindrome( string )\n    ( test = string.downcase.gsub( /[^a-z]/, \'\' ) ) == test.reverse\nend\n</code></pre>\n\n<p>But that feels like cheating, right? No pointers or anything! So here\'s a C version too, but without the lowercase and character stripping goodness:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint isPalindrome( char * string )\n{\n    char * i = string;\n    char * p = string;\n    while ( *++i ); while ( i &gt; p &amp;&amp; *p++ == *--i );\n    return i &lt;= p &amp;&amp; *i++ == *--p;\n}\nint main( int argc, char **argv )\n{\n    if ( argc != 2 )\n    {\n        fprintf( stderr, "Usage: %s &lt;word&gt;\\n", argv[0] );\n        return -1;\n    }\n    fprintf( stdout, "%s\\n", isPalindrome( argv[1] ) ? "yes" : "no" );\n    return 0;\n}\n</code></pre>\n\n<p>Well, that was fun - do I get the job ;^)</p>\n'}, {'answer_id': 52660, 'author': 'Wedge', 'author_id': 332, 'author_profile': 'https://Stackoverflow.com/users/332', 'pm_score': 3, 'selected': False, 'text': '<p>I\'m seeing a lot of incorrect answers here. Any correct solution needs to ignore whitespace and punctuation (and any non-alphabetic characters actually) and needs to be case insensitive.</p>\n\n<p>A few good example test cases are:</p>\n\n<p>"A man, a plan, a canal, Panama."</p>\n\n<p>"A Toyota\'s a Toyota."</p>\n\n<p>"A"</p>\n\n<p>""</p>\n\n<p>As well as some non-palindromes.</p>\n\n<p>Example solution in C# (note: empty and null strings are considered palindromes in this design, if this is not desired it\'s easy to change):</p>\n\n<pre><code>public static bool IsPalindrome(string palindromeCandidate)\n{\n    if (string.IsNullOrEmpty(palindromeCandidate))\n    {\n        return true;\n    }\n    Regex nonAlphaChars = new Regex("[^a-z0-9]");\n    string alphaOnlyCandidate = nonAlphaChars.Replace(palindromeCandidate.ToLower(), "");\n    if (string.IsNullOrEmpty(alphaOnlyCandidate))\n    {\n        return true;\n    }\n    int leftIndex = 0;\n    int rightIndex = alphaOnlyCandidate.Length - 1;\n    while (rightIndex &gt; leftIndex)\n    {\n        if (alphaOnlyCandidate[leftIndex] != alphaOnlyCandidate[rightIndex])\n        {\n            return false;\n        }\n        leftIndex++;\n        rightIndex--;\n    }\n    return true;\n}\n</code></pre>\n'}, {'answer_id': 52749, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 4, 'selected': False, 'text': '<p>A more Ruby-style rewrite of <a href="https://stackoverflow.com/questions/52002/how-to-check-if-the-given-string-is-palindrome#52328">Hal\'s Ruby version</a>:</p>\n\n<pre><code>class String\n  def palindrome?\n    (test = gsub(/[^A-Za-z]/, \'\').downcase) == test.reverse\n  end\nend\n</code></pre>\n\n<p>Now you can call <code>palindrome?</code> on any string.</p>\n'}, {'answer_id': 53009, 'author': 'Hostile', 'author_id': 5323, 'author_profile': 'https://Stackoverflow.com/users/5323', 'pm_score': 3, 'selected': False, 'text': '<p>C in the house. (not sure if you didn\'t want a C example here)</p>\n\n<pre><code>bool IsPalindrome(char *s)\n{\n    int  i,d;\n    int  length = strlen(s);\n    char cf, cb;\n\n    for(i=0, d=length-1 ; i &lt; length &amp;&amp; d &gt;= 0 ; i++ , d--)\n    {\n        while(cf= toupper(s[i]), (cf &lt; \'A\' || cf &gt;\'Z\') &amp;&amp; i &lt; length-1)i++;\n        while(cb= toupper(s[d]), (cb &lt; \'A\' || cb &gt;\'Z\') &amp;&amp; d &gt; 0       )d--;\n        if(cf != cb &amp;&amp; cf &gt;= \'A\' &amp;&amp; cf &lt;= \'Z\' &amp;&amp; cb &gt;= \'A\' &amp;&amp; cb &lt;=\'Z\')\n            return false;\n    }\n    return true;\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>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.</p>\n'}, {'answer_id': 53055, 'author': 'Vertigo', 'author_id': 5468, 'author_profile': 'https://Stackoverflow.com/users/5468', 'pm_score': 1, 'selected': False, 'text': "<p>Perl:</p>\n\n<pre><code>sub is_palindrome($)\n{\n  $s = lc(shift); # ignore case\n  $s =~ s/\\W+//g; # consider only letters, digits, and '_'\n  $s eq reverse $s;\n}\n</code></pre>\n\n<p>It ignores case and strips non-alphanumeric characters (it locale- and unicode- neutral).</p>\n"}, {'answer_id': 53148, 'author': 'SCdF', 'author_id': 1666, 'author_profile': 'https://Stackoverflow.com/users/1666', 'pm_score': 1, 'selected': False, 'text': '<p>Using Java, using <a href="http://commons.apache.org/" rel="nofollow noreferrer">Apache Commons</a> String Utils:</p>\n\n<pre><code>public boolean isPalindrome(String phrase) {\n  phrase = phrase.toLowerCase().replaceAll("[^a-z]", "");\n  return StringUtils.reverse(phrase).equals(phrase);\n}\n</code></pre>\n'}, {'answer_id': 53215, 'author': 'Pedro', 'author_id': 5488, 'author_profile': 'https://Stackoverflow.com/users/5488', 'pm_score': 0, 'selected': False, 'text': '<p>If we\'re looking for numbers and simple words, many correct answers have been given.</p>\n\n<p>However, if we\'re looking for what we generally see as palindromes in written language (e.g., "A dog, a panic, in a pagoda!"), the correct answer would be to iterate starting from both ends of the sentence, <em>skipping non-alphanumeric characters individually</em>, and returning false if any mismatches are found.</p>\n\n<pre><code>i = 0; j = length-1;\n\nwhile( true ) {\n  while( i &lt; j &amp;&amp; !is_alphanumeric( str[i] ) ) i++;\n  while( i &lt; j &amp;&amp; !is_alphanumeric( str[j] ) ) j--;\n\n  if( i &gt;= j ) return true;\n\n  if( tolower(string[i]) != tolower(string[j]) ) return false;\n  i++; j--;\n}\n</code></pre>\n\n<p></p>\n\n<p>Of course, stripping out non-valid characters, reversing the resulting string and comparing it to the original one also works. It comes down to what type of language you\'re working on.</p>\n'}, {'answer_id': 53505, 'author': 'tslocum', 'author_id': 1662, 'author_profile': 'https://Stackoverflow.com/users/1662', 'pm_score': 1, 'selected': False, 'text': "<p>I had to do this for a programming challenge, here's a snippet of my Haskell:</p>\n\n<pre><code>isPalindrome :: String -&gt; Bool\nisPalindrome n = (n == reverse n)\n</code></pre>\n"}, {'answer_id': 56204, 'author': 'Will Boyce', 'author_id': 5757, 'author_profile': 'https://Stackoverflow.com/users/5757', 'pm_score': 1, 'selected': False, 'text': '<p>Python:</p>\n\n<pre><code>if s == s[::-1]: return True\n</code></pre>\n\n<p>Java:</p>\n\n<pre><code>if (s.Equals(s.Reverse())) { return true; }\n</code></pre>\n\n<p>PHP:</p>\n\n<pre><code>if (s == strrev(s)) return true;\n</code></pre>\n\n<p>Perl:</p>\n\n<pre><code>if (s == reverse(s)) { return true; }\n</code></pre>\n\n<p>Erlang:</p>\n\n<pre><code>string:equal(S, lists:reverse(S)).\n</code></pre>\n'}, {'answer_id': 58575, 'author': 'prakash', 'author_id': 123, 'author_profile': 'https://Stackoverflow.com/users/123', 'pm_score': 0, 'selected': False, 'text': '<p>OCaml:</p>\n\n<pre><code>let rec palindrome s =\n  s = (tailrev s)\n</code></pre>\n\n<p><a href="http://www.cis.upenn.edu/~lhuang3/cse399-python/handouts/ocaml.ppt" rel="nofollow noreferrer">source</a></p>\n'}, {'answer_id': 59364, 'author': 'Alexander Stolz', 'author_id': 2450, 'author_profile': 'https://Stackoverflow.com/users/2450', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Lisp:</strong></p>\n\n<pre><code>(defun palindrome(x) (string= x (reverse x)))\n</code></pre>\n'}, {'answer_id': 63366, 'author': 'LepardUK', 'author_id': 44247, 'author_profile': 'https://Stackoverflow.com/users/44247', 'pm_score': 0, 'selected': False, 'text': '<pre><code>boolean IsPalindrome(string s) {\nreturn s = s.Reverse();\n}\n</code></pre>\n'}, {'answer_id': 68900, 'author': 'Michael Carman', 'author_id': 8233, 'author_profile': 'https://Stackoverflow.com/users/8233', 'pm_score': 1, 'selected': False, 'text': '<p>Perl:</p>\n\n<pre><code>sub is_palindrome {\n    my $s = lc shift; # normalize case\n    $s =~ s/\\W//g;    # strip non-word characters\n    return $s eq reverse $s;\n}\n</code></pre>\n'}, {'answer_id': 77508, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 2, 'selected': False, 'text': '<p>An obfuscated C version:</p>\n\n<pre><code>int IsPalindrome (char *s)\n{\n  char*a,*b,c=0;\n  for(a=b=s;a&lt;=b;c=(c?c==1?c=(*a&amp;~32)-65&gt;25u?*++a,1:2:c==2?(*--b&amp;~32)-65&lt;26u?3:2:c==3?(*b-65&amp;~32)-(*a-65&amp;~32)?*(b=s=0,a),4:*++a,1:0:*++b?0:1));\n  return s!=0;\n}\n</code></pre>\n'}, {'answer_id': 77620, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 2, 'selected': False, 'text': "<p>Note that in the above C++ solutions, there was some problems.</p>\n<p>One solution was inefficient because it passed an std::string by copy, and because it iterated over all the chars, instead of comparing only half the chars. Then, even when discovering the string was not a palindrome, it continued the loop, waiting its end before reporting &quot;false&quot;.</p>\n<p>The other was better, with a very small function, whose problem was that it was not able to test anything else than std::string. In C++, it is easy to extend an algorithm to a whole bunch of similar objects. By templating its std::string into &quot;T&quot;, it would have worked on both std::string, std::wstring, std::vector and std::deque. But without major modification because of the use of the operator &lt;, the std::list was out of its scope.</p>\n<p>My own solutions try to show that a C++ solution won't stop at working on the exact current type, but will strive to work an <em>anything</em> that behaves the same way, no matter the type. For example, I could apply my palindrome tests on std::string, on vector of int or on list of &quot;Anything&quot; as long as Anything was comparable through its operator = (build in types, as well as classes).</p>\n<p>Note that the template can even be extended with an optional type that can be used to compare the data. For example, if you want to compare in a case insensitive way, or even compare similar characters (like è, é, ë, ê and e).</p>\n<p>Like king Leonidas would have said: <em>&quot;Templates ? This is C++ !!!&quot;</em></p>\n<p>So, in C++, there are at least 3 major ways to do it, each one leading to the other:</p>\n<h2>Solution A: In a c-like way</h2>\n<p>The problem is that until C++0X, we can't consider the std::string array of chars as contiguous, so we must &quot;cheat&quot; and retrieve the c_str() property. As we are using it in a read-only fashion, it should be ok...</p>\n<hr />\n<pre><code>bool isPalindromeA(const std::string &amp; p_strText)\n{\n   if(p_strText.length() &lt; 2) return true ;\n   const char * pStart = p_strText.c_str() ;             \n   const char * pEnd = pStart + p_strText.length() - 1 ; \n\n   for(; pStart &lt; pEnd; ++pStart, --pEnd)\n   {\n      if(*pStart != *pEnd)\n      {\n         return false ;\n      }\n   }\n\n   return true ;\n}\n</code></pre>\n<hr />\n<h2>Solution B: A more &quot;C++&quot; version</h2>\n<p>Now, we'll try to apply the same solution, but to any C++ container with random access to its items through operator []. For example, any std::basic_string, std::vector, std::deque, etc. Operator [] is constant access for those containers, so we won't lose undue speed.</p>\n<hr />\n<pre><code>template &lt;typename T&gt;\nbool isPalindromeB(const T &amp; p_aText)\n{\n   if(p_aText.empty()) return true ;\n   typename T::size_type iStart = 0 ;\n   typename T::size_type iEnd = p_aText.size() - 1 ;\n\n   for(; iStart &lt; iEnd; ++iStart, --iEnd)\n   {\n      if(p_aText[iStart] != p_aText[iEnd])\n      {\n         return false ;\n      }\n   }\n\n   return true ;\n}\n</code></pre>\n<hr />\n<h2>Solution C: Template powah !</h2>\n<p>It will work with almost any unordered STL-like container with bidirectional iterators\nFor example, any std::basic_string, std::vector, std::deque, std::list, etc.\nSo, this function can be applied on all STL-like containers with the following conditions:\n1 - T is a container with bidirectional iterator\n2 - T's iterator points to a comparable type (through operator =)</p>\n<hr />\n<pre><code>template &lt;typename T&gt;\nbool isPalindromeC(const T &amp; p_aText)\n{\n   if(p_aText.empty()) return true ;\n   typename T::const_iterator pStart = p_aText.begin() ;\n   typename T::const_iterator pEnd = p_aText.end() ;\n   --pEnd ;\n\n   while(true)\n   {\n      if(*pStart != *pEnd)\n      {\n         return false ;\n      }\n\n      if((pStart == pEnd) || (++pStart == pEnd))\n      {\n         return true ;\n      }\n\n      --pEnd ;\n   }\n}\n</code></pre>\n<hr />\n"}, {'answer_id': 228706, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>c++:</p>\n\n<pre><code>bool is_palindrome(const string &amp;s)\n{\n    return equal( s.begin(), s.begin()+s.length()/2, s.rbegin());\n}\n</code></pre>\n'}, {'answer_id': 228707, 'author': 'Shabbyrobe', 'author_id': 15004, 'author_profile': 'https://Stackoverflow.com/users/15004', 'pm_score': 0, 'selected': False, 'text': '<p>There isn\'t a <em>single</em> solution on here which takes into account that a palindrome can also be based on word units, not just character units.</p>\n\n<p>Which means that none of the given solutions return true for palindromes like "Girl, bathing on Bikini, eyeing boy, sees boy eyeing bikini on bathing girl".</p>\n\n<p>Here\'s a hacked together version in C#. I\'m sure it doesn\'t need the regexes, but it does work just as well with the above bikini palindrome as it does with "A man, a plan, a canal-Panama!".</p>\n\n<pre><code>    static bool IsPalindrome(string text)\n    {\n        bool isPalindrome = IsCharacterPalindrome(text);\n        if (!isPalindrome)\n        {\n            isPalindrome = IsPhrasePalindrome(text);\n        }\n        return isPalindrome;\n    }\n\n    static bool IsCharacterPalindrome(string text)\n    {\n        String clean = Regex.Replace(text.ToLower(), "[^A-z0-9]", String.Empty, RegexOptions.Compiled);\n        bool isPalindrome = false;\n        if (!String.IsNullOrEmpty(clean) &amp;&amp; clean.Length &gt; 1)\n        {\n            isPalindrome = true;\n            for (int i = 0, count = clean.Length / 2 + 1; i &lt; count; i++)\n            {\n                if (clean[i] != clean[clean.Length - 1 - i])\n                {\n                    isPalindrome = false; break;\n                }\n            }\n        }\n        return isPalindrome;\n    }\n\n    static bool IsPhrasePalindrome(string text)\n    {\n        bool isPalindrome = false;\n        String clean = Regex.Replace(text.ToLower(), @"[^A-z0-9\\s]", " ", RegexOptions.Compiled).Trim();\n        String[] words = Regex.Split(clean, @"\\s+");\n        if (words.Length &gt; 1)\n        {\n            isPalindrome = true;\n            for (int i = 0, count = words.Length / 2 + 1; i &lt; count; i++)\n            {\n                if (words[i] != words[words.Length - 1 - i])\n                {\n                    isPalindrome = false; break;\n                }\n            }\n        }\n        return isPalindrome;\n    }\n</code></pre>\n'}, {'answer_id': 263449, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I haven\'t seen any recursion yet, so here goes...</p>\n\n<pre><code>import re\n\nr = re.compile("[^0-9a-zA-Z]")\n\ndef is_pal(s):\n\n    def inner_pal(s):\n        if len(s) == 0:\n            return True\n        elif s[0] == s[-1]:\n            return inner_pal(s[1:-1])\n        else:\n            return False\n\n    r = re.compile("[^0-9a-zA-Z]")\n    return inner_pal(r.sub("", s).lower())\n</code></pre>\n'}, {'answer_id': 277721, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>This is all good, but is there a way to do better algorithmically? I was once asked in a interview to recognize a palindrome in linear time and <em>constant space</em>.</p>\n\n<p>I couldn't think of anything then and I still can't. </p>\n\n<p>(If it helps, I asked the interviewer what the answer was. He said you can construct a pair of hash functions such that they hash a given string to the same value if and only if that string is a palindrome. I have no idea how you would actually make this pair of functions.)</p>\n"}, {'answer_id': 277727, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 2, 'selected': False, 'text': '<h2>C++</h2>\n\n<pre><code>std::string a = "god";\nstd::string b = "lol";\n\nstd::cout &lt;&lt; (std::string(a.rbegin(), a.rend()) == a) &lt;&lt; " " \n          &lt;&lt; (std::string(b.rbegin(), b.rend()) == b);\n</code></pre>\n\n<h2>Bash</h2>\n\n<pre><code>function ispalin { [ "$( echo -n $1 | tac -rs . )" = "$1" ]; }\necho "$(ispalin god &amp;&amp; echo yes || echo no), $(ispalin lol &amp;&amp; echo yes || echo no)"\n</code></pre>\n\n<h2>Gnu Awk</h2>\n\n<pre><code>/* obvious solution */\nfunction ispalin(cand, i) { \n    for(i=0; i&lt;length(cand)/2; i++) \n        if(substr(cand, length(cand)-i, 1) != substr(cand, i+1, 1)) \n            return 0; \n    return 1; \n}\n\n/* not so obvious solution. cough cough */\n{ \n    orig = $0;\n    while($0) { \n        stuff = stuff gensub(/^.*(.)$/, "\\\\1", 1); \n        $0 = gensub(/^(.*).$/, "\\\\1", 1); \n    }\n    print (stuff == orig); \n}\n</code></pre>\n\n<h2>Haskell</h2>\n\n<p>Some brain dead way doing it in Haskell</p>\n\n<pre><code>ispalin :: [Char] -&gt; Bool\nispalin a = a == (let xi (y:my) = (xi my) ++ [y]; xi [] = [] in \\x -&gt; xi x) a\n</code></pre>\n\n<h2>Plain English</h2>\n\n<p><code>"Just reverse the string and if it is the same as before, it\'s a palindrome"</code></p>\n'}, {'answer_id': 278003, 'author': 'reefnet_alex', 'author_id': 2745, 'author_profile': 'https://Stackoverflow.com/users/2745', 'pm_score': 0, 'selected': False, 'text': "<p>The solutions which strip out any chars that don't fall between A-Z or a-z are very English centric. Letters with diacritics such as à or é would be stripped! </p>\n\n<p>According to Wikipedia: </p>\n\n<blockquote>\n  <p>The treatment of diacritics varies. In languages such as Czech and Spanish, letters with diacritics or accents (except tildes) are not given a separate place in the alphabet, and thus preserve the palindrome whether or not the repeated letter has an ornamentation. However, in Swedish and other Nordic languages, A and A with a ring (å) are distinct letters and must be mirrored exactly to be considered a true palindrome.</p>\n</blockquote>\n\n<p>So to cover many other languages it would be better to use collation to convert diacritical marks to their equivalent non diacritic or leave alone as appropriate and then strip whitespace and punctuation only before comparing.</p>\n"}, {'answer_id': 371523, 'author': 'LeppyR64', 'author_id': 16592, 'author_profile': 'https://Stackoverflow.com/users/16592', 'pm_score': 0, 'selected': False, 'text': '<pre><code>set l = index of left most character in word\nset r = index of right most character in word\n\nloop while(l &lt; r)\nbegin\n  if letter at l does not equal letter at r\n    word is not palindrome\n  else\n     increase l and decrease r\nend\nword is palindrome\n</code></pre>\n'}, {'answer_id': 430317, 'author': 'Vadim Ferderer', 'author_id': 24142, 'author_profile': 'https://Stackoverflow.com/users/24142', 'pm_score': 0, 'selected': False, 'text': '<p>Efficient C++ version:</p>\n\n<pre><code>template&lt; typename Iterator &gt;\nbool is_palindrome( Iterator first, Iterator last, std::locale const&amp; loc = std::locale("") )\n{\n    if ( first == last )\n        return true;\n\n    for( --last; first &lt; last; ++first, --last )\n    {\n        while( ! std::isalnum( *first, loc ) &amp;&amp; first &lt; last )\n            ++first;\n        while( ! std::isalnum( *last, loc ) &amp;&amp; first &lt; last )\n            --last;\n        if ( std::tolower( *first, loc ) != std::tolower( *last, loc ) )\n            return false;\n    }\n    return true;\n}\n</code></pre>\n'}, {'answer_id': 430363, 'author': 'Dave Sherohman', 'author_id': 18914, 'author_profile': 'https://Stackoverflow.com/users/18914', 'pm_score': 0, 'selected': False, 'text': '<p>Here are two more Perl versions, neither of which uses <code>reverse</code>.  Both use the basic algorithm of comparing the first character of the string to the last, then discarding them and repeating the test, but they use different methods of getting at the individual characters (the first peels them off one at a time with a regex, the second <code>split</code>s the string into an array of characters).</p>\n\n<pre><code>#!/usr/bin/perl\n\nmy @strings = ("A man, a plan, a canal, Panama.", "A Toyota\'s a Toyota.", \n               "A", "", "As well as some non-palindromes.");\n\nfor my $string (@strings) {\n  print is_palindrome($string)  ? "\'$string\' is a palindrome (1)\\n"\n                                : "\'$string\' is not a palindrome (1)\\n";\n  print is_palindrome2($string) ? "\'$string\' is a palindrome (2)\\n"\n                                : "\'$string\' is not a palindrome (2)\\n";\n} \n\nsub is_palindrome {\n  my $str = lc shift;\n  $str =~ tr/a-z//cd;\n\n  while ($str =~ s/^(.)(.*)(.)$/\\2/) {\n    return unless $1 eq $3;\n  }\n\n  return 1;\n} \n\nsub is_palindrome2 {\n  my $str = lc shift;\n  $str =~ tr/a-z//cd;\n  my @chars = split \'\', $str;\n\n  while (@chars &amp;&amp; shift @chars eq pop @chars) {};\n\n  return scalar @chars &lt;= 1;\n} \n</code></pre>\n'}, {'answer_id': 430393, 'author': 'Ta01', 'author_id': 7280, 'author_profile': 'https://Stackoverflow.com/users/7280', 'pm_score': 0, 'selected': False, 'text': '<p>Easy mode in C#, only using Base Class Libraries</p>\n\n<p>Edit: just saw someone did Array.Reverse also  </p>\n\n<pre><code>public bool IsPalindrome(string s)\n            {\n                if (String.IsNullOrEmpty(s))\n                {\n                    return false;\n                }\n\n                else\n                {\n                    char[] t = s.ToCharArray();\n                    Array.Reverse(t);\n                    string u = new string(t);\n                    if (s.ToLower() == u.ToLower())\n                    {\n                        return true;\n                    }\n                }\n\n                return false;\n            }\n</code></pre>\n'}, {'answer_id': 430444, 'author': 'BBetances', 'author_id': 53599, 'author_profile': 'https://Stackoverflow.com/users/53599', 'pm_score': 0, 'selected': False, 'text': "<p>Here's another for C# that I used when doing a sample server control. It can be found in the book ASP.NET 3.5 Step by Step (MS Press). It's two methods, one to strip non-alphanumerics, and another to check for a palindrome.</p>\n\n<pre><code>protected string StripNonAlphanumerics(string str)\n{\n    string strStripped = (String)str.Clone();\n    if (str != null)\n    {\n        char[] rgc = strStripped.ToCharArray();\n        int i = 0;\n        foreach (char c in rgc)\n        {\n            if (char.IsLetterOrDigit(c))\n            {\n                i++;\n            }\n            else\n            {\n                strStripped = strStripped.Remove(i, 1);\n            }\n        }\n    }\n    return strStripped;\n}\nprotected bool CheckForPalindrome()\n{\n    if (this.Text != null)\n    {\n        String strControlText = this.Text;\n        String strTextToUpper = null;\n        strTextToUpper = Text.ToUpper();\n        strControlText =\n                    this.StripNonAlphanumerics(strTextToUpper);\n        char[] rgcReverse = strControlText.ToCharArray();\n        Array.Reverse(rgcReverse);\n        String strReverse = new string(rgcReverse);\n        if (strControlText == strReverse)\n        {\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n    else\n    {\n        return false;\n    }\n}\n</code></pre>\n"}, {'answer_id': 430483, 'author': 'hughdbrown', 'author_id': 10293, 'author_profile': 'https://Stackoverflow.com/users/10293', 'pm_score': 0, 'selected': False, 'text': '<p>Const-correct C/C++ pointer solution. Minimal operations in loop.</p>\n\n<pre><code>int IsPalindrome (const char *str)\n{\n    const unsigned len = strlen(str);\n    const char *end = &amp;str[len-1];\n    while (str &lt; end)\n        if (*str++ != *end--)\n            return 0;\n    return 1;\n}\n</code></pre>\n'}, {'answer_id': 659809, 'author': 'Ascalonian', 'author_id': 65230, 'author_profile': 'https://Stackoverflow.com/users/65230', 'pm_score': 2, 'selected': False, 'text': '<p>A simple Java solution:</p>\n\n<pre><code>public boolean isPalindrome(String testString) {\n    StringBuffer sb = new StringBuffer(testString);\n    String reverseString = sb.reverse().toString();\n\n    if(testString.equalsIgnoreCase(reverseString)) {\n        return true;\n    else {\n        return false;\n    }\n}\n</code></pre>\n'}, {'answer_id': 1039466, 'author': 'patjbs', 'author_id': 79256, 'author_profile': 'https://Stackoverflow.com/users/79256', 'pm_score': 1, 'selected': False, 'text': "<p>My 2c.  Avoids overhead of full string reversal everytime, taking advantage of shortcircuiting to return as soon as the nature of the string is determined.  Yes, you should condition your string first, but IMO that's the job of another function.</p>\n\n<p><strong>In C#</strong></p>\n\n<pre><code>    /// &lt;summary&gt;\n    /// Tests if a string is a palindrome\n    /// &lt;/summary&gt;\n    public static bool IsPalindrome(this String str)\n    {\n        if (str.Length == 0) return false;\n        int index = 0;\n        while (index &lt; str.Length / 2)\n            if (str[index] != str[str.Length - ++index]) return false;\n\n        return true;\n    }\n</code></pre>\n"}, {'answer_id': 1039549, 'author': 'Matchu', 'author_id': 107415, 'author_profile': 'https://Stackoverflow.com/users/107415', 'pm_score': 2, 'selected': False, 'text': '<h2>Ruby:</h2>\n\n<pre><code>class String\n    def is_palindrome?\n        letters_only = gsub(/\\W/,\'\').downcase\n        letters_only == letters_only.reverse\n    end\nend\n\nputs \'abc\'.is_palindrome? # =&gt; false\nputs \'aba\'.is_palindrome? # =&gt; true\nputs "Madam, I\'m Adam.".is_palindrome? # =&gt; true\n</code></pre>\n'}, {'answer_id': 1078441, 'author': 'Alexander Stolz', 'author_id': 2450, 'author_profile': 'https://Stackoverflow.com/users/2450', 'pm_score': 0, 'selected': False, 'text': '<p><strong>Scala</strong></p>\n\n<pre><code>def pal(s:String) = Symbol(s) equals Symbol(s.reverse)\n</code></pre>\n'}, {'answer_id': 1115333, 'author': 'AlejandroR', 'author_id': 120007, 'author_profile': 'https://Stackoverflow.com/users/120007', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n  <p><strong>Prolog</strong></p>\n</blockquote>\n\n<pre><code>palindrome(B, R) :-\npalindrome(B, R, []).\n\npalindrome([], R, R).\npalindrome([X|B], [X|R], T) :-\npalindrome(B, R, [X|T]).\n</code></pre>\n'}, {'answer_id': 2049311, 'author': 'Pritam Karmakar', 'author_id': 208513, 'author_profile': 'https://Stackoverflow.com/users/208513', 'pm_score': 0, 'selected': False, 'text': '<pre><code>    public bool IsPalindrome(string s)\n    {\n        string formattedString = s.Replace(" ", string.Empty).ToLower();\n        for (int i = 0; i &lt; formattedString.Length / 2; i++)\n        {\n            if (formattedString[i] != formattedString[formattedString.Length - 1 - i])\n                return false;\n        }\n        return true;\n    }\n</code></pre>\n\n<p>This method will work for sting like "Was it a rat I saw". But I feel we need to eliminate special character through Regex.</p>\n'}, {'answer_id': 2751730, 'author': 'rockvista', 'author_id': 1996230, 'author_profile': 'https://Stackoverflow.com/users/1996230', 'pm_score': 0, 'selected': False, 'text': "<p>C# Version:</p>\n\n<p>Assumes MyString to be a char[], Method return after verification of the string, it ignores space and &lt;,>, but this can be extended to ignore more, probably impleemnt a regex match of ignore list.</p>\n\n<pre><code>public bool IsPalindrome()\n            if (MyString.Length == 0)\n                return false;\n\n            int len = MyString.Length - 1;\n\n            int first = 0;\n            int second = 0;\n\n            for (int i = 0, j = len; i &lt;= len / 2; i++, j--)\n            {\n                while (i&lt;j &amp;&amp; MyString[i] == ' ' || MyString[i] == ',')\n                    i++;\n\n                while(j&gt;i &amp;&amp; MyString[j] == ' ' || MyString[j] == ',')\n                    j--;\n\n                if ((i == len / 2) &amp;&amp; (i == j))\n                    return true;\n\n                first = MyString[i] &gt;= 97 &amp;&amp; MyString[i] &lt;= 122 ? MyString[i] - 32 : MyString[i];\n                second = MyString[j] &gt;= 97 &amp;&amp; MyString[j] &lt;= 122 ? MyString[j] - 32 : MyString[j];\n\n                if (first != second)\n                    return false;\n            }\n\n            return true;\n  }\n</code></pre>\n\n<p>Quick test cases</p>\n\n<p>negative\n1. ABCDA \n2. AB CBAG\n3. A#$BDA\n4. NULL/EMPTY</p>\n\n<p>positive\n1. ABCBA\n2. A, man a plan a canal,,Panama\n3. ABC BA\n4. M\n5. ACCB</p>\n\n<p>let me know any thoghts/errors.</p>\n"}, {'answer_id': 5130209, 'author': 'Micke', 'author_id': 635969, 'author_profile': 'https://Stackoverflow.com/users/635969', 'pm_score': 0, 'selected': False, 'text': '<p>How about this PHP example: </p>\n\n<pre><code>function noitcnuf( $returnstrrevverrtsnruter, $functionnoitcnuf) {\n    $returnstrrev  = "returnstrrevverrtsnruter";\n    $verrtsnruter = $functionnoitcnuf;\n    return (strrev ($verrtsnruter) == $functionnoitcnuf) ; \n}\n</code></pre>\n'}, {'answer_id': 5494118, 'author': 'Bubbles', 'author_id': 631423, 'author_profile': 'https://Stackoverflow.com/users/631423', 'pm_score': 0, 'selected': False, 'text': '<pre><code>public static boolean isPalindrome( String str ) {\n    int count = str.length() ;\n    int i, j = count - 1 ;\n    for ( i = 0 ; i &lt; count ; i++ ) {\n        if ( str.charAt(i) != str.charAt(j) ) return false ;\n        if ( i == j ) return true ;\n        j-- ;\n    }\n    return true ;\n}\n</code></pre>\n'}, {'answer_id': 8181718, 'author': 'Ram', 'author_id': 50418, 'author_profile': 'https://Stackoverflow.com/users/50418', 'pm_score': 1, 'selected': False, 'text': '<p>Erlang is awesome</p>\n\n<pre><code>palindrome(L) -&gt; palindrome(L,[]).\n\npalindrome([],_) -&gt; false;\npalindrome([_|[]],[]) -&gt; true;\npalindrome([_|L],L) -&gt; true;\npalindrome(L,L) -&gt; true;\npalindrome([H|T], Acc) -&gt; palindrome(T, [H|Acc]).\n</code></pre>\n'}, {'answer_id': 8672758, 'author': 'Mushimo', 'author_id': 456206, 'author_profile': 'https://Stackoverflow.com/users/456206', 'pm_score': 1, 'selected': False, 'text': '<p>No solution using JavaScript yet?</p>\n\n<pre><code>function palindrome(s) {\n  var l = 0, r = s.length - 1;\n  while (l &lt; r) if (s.charAt(left++) !== s.charAt(r--)) return false;\n  return true\n}\n</code></pre>\n'}, {'answer_id': 8733562, 'author': 'Justin', 'author_id': 950252, 'author_profile': 'https://Stackoverflow.com/users/950252', 'pm_score': 0, 'selected': False, 'text': '<p>If you can use Java APIs and additional storage:</p>\n\n<pre><code>public static final boolean isPalindromeWithAdditionalStorage(String string) {\n    String reversed = new StringBuilder(string).reverse().toString();\n    return string.equals(reversed);\n}\n</code></pre>\n\n<p>In can need an in-place method for Java:</p>\n\n<pre><code>public static final boolean isPalindromeInPlace(String string) {\n    char[] array = string.toCharArray();\n    int length = array.length-1;\n    int half = Math.round(array.length/2);\n    char a,b;\n    for (int i=length; i&gt;=half; i--) {\n        a = array[length-i];\n        b = array[i];\n        if (a != b) return false;\n    }\n    return true;\n}\n</code></pre>\n'}, {'answer_id': 9305682, 'author': 'melsk', 'author_id': 809694, 'author_profile': 'https://Stackoverflow.com/users/809694', 'pm_score': 0, 'selected': False, 'text': '<p><b>Regular Approach:</b></p>\n\n<pre><code>flag = True // Assume palindrome is true\nfor i from 0 to n/2 \n { compare element[i] and element[n-i-1] // 0 to n-1\n   if not equal set flag = False\n   break }\nreturn flag\n</code></pre>\n\n<p>There is a better machine optimized method which uses XORs but has the same complexity <br/><br/>\n<b>XOR approach</b>:</p>\n\n<pre><code>n = length of string\nmid_element = element[n/2 +1]\nfor i from 0 to n\n{ t_xor = element[i] xor element[i+1] }\nif n is odd compare mid_element and t_xor\nelse check t_xor is zero\n</code></pre>\n'}, {'answer_id': 14772912, 'author': 'user2039532', 'author_id': 2039532, 'author_profile': 'https://Stackoverflow.com/users/2039532', 'pm_score': 0, 'selected': False, 'text': '<pre><code>public class palindrome {\npublic static void main(String[] args) {\n    StringBuffer strBuf1 = new StringBuffer("malayalam");\n    StringBuffer strBuf2 = new StringBuffer("malayalam");\n    strBuf2.reverse();\n\n\n    System.out.println(strBuf2);\n    System.out.println((strBuf1.toString()).equals(strBuf2.toString()));\n    if ((strBuf1.toString()).equals(strBuf2.toString()))\n        System.out.println("palindrome");\n    else\n        System.out.println("not a palindrome");\n    }\n}   \n</code></pre>\n'}, {'answer_id': 14906430, 'author': 'Rhys Ulerich', 'author_id': 103640, 'author_profile': 'https://Stackoverflow.com/users/103640', 'pm_score': 0, 'selected': False, 'text': '<p>A case-insensitive, <code>const</code>-friendly version in plain C that ignores non-alphanumeric characters (e.g. whitespace / punctuation). It therefore will actually pass on classics like "A man, a plan, a canal, Panama".</p>\n\n<pre><code>int ispalin(const char *b)\n{\n    const char *e = b;\n    while (*++e);\n    while (--e &gt;= b)\n    {\n        if (isalnum(*e))\n        {\n            while (*b &amp;&amp; !isalnum(*b)) ++b;\n            if (toupper(*b++) != toupper(*e)) return 0;\n        }\n    }\n    return 1;\n}\n</code></pre>\n'}, {'answer_id': 19893643, 'author': 'Adrian Bratu', 'author_id': 1161008, 'author_profile': 'https://Stackoverflow.com/users/1161008', 'pm_score': 0, 'selected': False, 'text': '<p>The interviewer will be looking for some logic on how you will be approaching this problem:\nPlease consider the following java code:</p>\n\n<ol>\n<li>always check if the input string is null</li>\n<li>check your base cases.</li>\n<li>format your string accordingly (remove anything that is not a character/digit</li>\n<li>Most likely they do not want to see if you know the reverse function, and a comparison, but rather if you are able to answer the question using a loop and indexing.</li>\n<li><p>shortcut return as soon as you know your answer and do not waste resources for nothing.</p>\n\n<p>public static boolean isPalindrome(String s) {</p>\n\n<pre><code>if (s == null || s.length() == 0 || s.length() == 1)\n    return false;\n\nString ss = s.toLowerCase().replaceAll("/[^a-z]/", "");\n\nfor (int i = 0; i &lt; ss.length()/2; i++) \n    if (ss.charAt(i) != ss.charAt(ss.length() - 1 - i))\n        return false;\nreturn true;\n</code></pre>\n\n<p>}</p></li>\n</ol>\n'}, {'answer_id': 23638086, 'author': 'sam_rox', 'author_id': 3577754, 'author_profile': 'https://Stackoverflow.com/users/3577754', 'pm_score': 0, 'selected': False, 'text': '<p>Java with stacks.</p>\n\n<pre><code>public class StackPalindrome {\n    public boolean isPalindrome(String s) throws OverFlowException,EmptyStackException{\n        boolean isPal=false;\n        String pal="";\n        char letter;\n        if (s==" ")\n            return true;\n        else{   \n            s=s.toLowerCase();\n            for(int i=0;i&lt;s.length();i++){\n\n            letter=s.charAt(i);\n\n            char[] alphabet={\'a\',\'b\',\'c\',\'d\',\'e\',\'f\',\'g\',\'h\',\'i\',\'j\',\'k\',\'l\',\'m\',\'n\',\'o\',\'p\',\'q\',\'r\',\'s\',\'t\',\'u\',\'v\',\'w\',\'x\',\'y\',\'z\'};\n            for(int j=0; j&lt;alphabet.length;j++){\n                /*removing punctuations*/\n                if ((String.valueOf(letter)).equals(String.valueOf(alphabet[j]))){\n                    pal +=letter;\n                }\n\n            }\n\n        }\n        int len=pal.length();\n        char[] palArray=new char[len];\n        for(int r=0;r&lt;len;r++){\n            palArray[r]=pal.charAt(r);\n        }\n        ArrayStack palStack=new ArrayStack(len);\n        for(int k=0;k&lt;palArray.length;k++){\n            palStack.push(palArray[k]);\n        }\n        for (int i=0;i&lt;len;i++){\n\n            if ((palStack.topAndpop()).equals(palArray[i]))\n                isPal=true;\n            else \n                isPal=false;\n        }\n    return isPal;\n    }\n}\npublic static void main (String args[]) throws EmptyStackException,OverFlowException{\n\n    StackPalindrome s=new StackPalindrome();\n    System.out.println(s.isPalindrome("“Ma,” Jerome raps pot top, “Spare more jam!”"));\n}\n</code></pre>\n'}, {'answer_id': 24759363, 'author': 'Pavan tej', 'author_id': 2063399, 'author_profile': 'https://Stackoverflow.com/users/2063399', 'pm_score': 0, 'selected': False, 'text': '<pre><code>//Single program for Both String or Integer to check palindrome\n\n//In java with out using string functions like reverse and equals method also and display matching characters also\n\npackage com.practice;\n\nimport java.util.Scanner;\n\npublic class Pallindrome {\n\n        public static void main(String args[]) {\n        Scanner sc=new Scanner(System.in);\n        int i=0,j=0,k,count=0;\n        String input,temp;\n        System.out.println("Enter the String or Integer");\n        input=sc.nextLine();\n        temp=input;\n        k=temp.length()-1;\n        for(i=0;i&lt;=input.length()-1;i++) {\n            if(input.charAt(j)==temp.charAt(k)) {\n                count++;\n            }\n            //For matching characters\n            j++;\n            k--;\n        }\n                System.out.println("Matching Characters = "+count);\n\n        if(count==input.length()) {\n            System.out.println("It\'s a pallindrome");\n        }\n        else {\n            System.out.println("It\'s not a pallindrome");\n        }\n\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 29174567, 'author': 'arsho', 'author_id': 3129414, 'author_profile': 'https://Stackoverflow.com/users/3129414', 'pm_score': 1, 'selected': False, 'text': '<p>Simple <strong>JavaScript</strong> solution. Run code snippet for demo.</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function checkPalindrome(line){\r\n      reverse_line=line.split("").reverse().join("");\r\n      return line==reverse_line;\r\n  }\r\nalert("checkPalindrome(radar): "+checkPalindrome("radar"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 29587590, 'author': 'Confuse', 'author_id': 3886922, 'author_profile': 'https://Stackoverflow.com/users/3886922', 'pm_score': 0, 'selected': False, 'text': '<pre><code>public static boolean isPalindrome(String str) {\n    return str.equals(new StringBuilder(str).reverse().toString());\n}\n</code></pre>\n\n<p>for versions of Java earlier than 1.5,</p>\n\n<pre><code>public static boolean isPalindrome(String str) {\n    return str.equals(new StringBuffer().append(str).reverse().toString());\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public static boolean istPalindrom(char[] word){\n    int i1 = 0;\n    int i2 = word.length - 1;\n    while (i2 &gt; i1) {\n        if (word[i1] != word[i2]) {\n            return false;\n        }\n        ++i1;\n        --i2;\n    }\n    return true;\n}\n</code></pre>\n'}, {'answer_id': 32550261, 'author': 'mockee', 'author_id': 468712, 'author_profile': 'https://Stackoverflow.com/users/468712', 'pm_score': 0, 'selected': False, 'text': "<pre><code>// JavaScript Version.\nfunction isPalindrome(str) { \n  str = str.replace(/[^a-zA-Z]/g, '')\n  return str.split('').reverse().join('').toUpperCase() === str.toUpperCase()       \n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/52008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1782/']