Amazon.com Widgets Fun Code of the Week #1

Fun Code of the Week #1

By Nick at October 06, 2011 11:20
Filed Under: Delphi, Fun Code
unit uIsPalindrome;

interface

function IsPalindrome(const aString: string): Boolean;

implementation

uses
       Spring.Collections
     , {$IF CompilerVersion >= 230}System.{$IFEND}SysUtils
     ;

function CleanString(const aString: string): string;
var
  C: char;
begin
  // Remove all non-alpha chars and make all lower case
  // Spaces don't matter, so let's count only letters
  Result := '';
  for C in LowerCase(aString) do
  begin
    if CharInSet(C, ['a'..'z', 'A'..'Z']) then
    begin
      Result := Result + C;
    end;
  end;
end;

function IsPalindrome(const aString: string): Boolean;
var
  Stack: IStack<Char>;
  C: Char;
  NoSpaces: string;
  Temp: string;
begin
  NoSpaces :=  CleanString(aString);

  Stack := TCollections.CreateStack<Char>;
  for C in NoSpaces do
  begin
    Stack.Push(C);
  end;
  Temp := '';
  repeat
    Temp := Temp + Stack.Pop;
  until Stack.Count = 0;
  Result := Temp = NoSpaces;
end;

end.

Added: I always enjoy posting code like this. Note that it is entitled "Fun Code", not "Highly optimized, perfectly written Code". ;-)

blog comments powered by Disqus

My Book

A Pithy Quote for You

"No concept is so difficult that it cannot be conquered by the repeated attacks of the ordinary mind"    –  Morrison Hodges, MD (My Dad)

Amazon Gift Cards

General Disclaimer

The views I express here are entirely my own and not necessarily those of any other rational person or organization.  However, I strongly recommend that you agree with pretty much everything I say because, well, I'm right.  Most of the time. Except when I'm not, in which case, you shouldn't agree with me.