Sherlock and Anagrams

  • + 0 comments

    Perl:

    sub sherlockAndAnagrams {
        my $s = shift;
        my @res;
        my %h;
        my $cnt = 0;
        
        for (my $i = 0; $i < length($s); $i++){
            for (my $j = $i + 1; $j <= length($s); $j++) {
                push(@res, substr($s, $i, $j - $i));
            }
        }
        
        my @sorted = map {join("", sort {$a cmp $b } split("", $_))} @res;
        foreach (@sorted) {
            $h{$_} += 1;
        }
        foreach (values(%h)) {
            $cnt += $_ * ($_ - 1) / 2 if ($_ > 1);
        }
        
        return $cnt;
    }