使用hash [Anam]比较Anagram的两个字符串

问题描述 投票:-5回答:1

我是新来的perl。任何人都可以举例说明perl代码,用于检测使用哈希值给定字符串之间的字符串。两个字符串 - 池和马球。

perl hash anagram
1个回答
1
投票
sub key(_) { join "", sort split //, $_[0] }

if (key("pool") eq key("polo") {
   say "Pool and polo are anagrams of each other.";
} else {
   say "Pool and polo aren't anagrams of each other.";
}

如果你有一本字典,

sub key(_) { join "", sort split //, $_[0] }

my $dict_qfn = "...";
my $search = "pool";

my %anagrams;
{
   open(my $fh, '<', $dict_qfn)
      or die("Can't open \"$dict_qfn\": $!\n");

   while (<$fh>) {
      chomp;
      push @{ $anagrams{ key($_) } }, $_;
   }
}

my @results = grep { $_ ne $search } @{ $anagrams{$search} // [] };
say "Anagrams of $search: ".( @results ? "@results" : "[none]" );
© www.soinside.com 2019 - 2024. All rights reserved.