Created
October 4, 2016 02:16
-
-
Save lestrrat/6d585b4b9e4e5980030eeed39704ea13 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use feature 'say'; | |
sub is_anagram { | |
my ($s1, $s2) = @_; | |
my %chars1; | |
my %chars2; | |
for my $c (split //, $s1) { | |
$chars1{$c}++; | |
} | |
for my $c (split //, $s2) { | |
if (not exists $chars1{$c}) { | |
return # early exit | |
} | |
$chars2{$c}++; | |
} | |
for my $k (keys %chars1) { | |
if (not exists $chars2{$k}) { | |
return | |
} | |
if ($chars2{$k} != $chars1{$k}) { | |
return | |
} | |
} | |
return 1 | |
} | |
sub check_and_report { | |
my($s1, $s2) = @_; | |
say "$s1 and $s2 -> ", is_anagram($s1, $s2) ? "is anagram" : "is NOT anagram"; | |
} | |
check_and_report("eros", "rose"); | |
check_and_report("eros", "roses"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment