Sherlock and the Valid String

  • + 0 comments

    Perl:

    sub isValid {
        my @s = split("", shift);
        
        my %h;
        my %c;
    
        foreach (@s) {
            $h{$_} +=1;
        }
        foreach (values(%h)) {
            $c{$_} +=1;
        }
    
        return "YES" if (keys(%c) == 1);    
        
        if (keys %c == 2) {
            my @keys = keys(%c);
            my ($freq1, $freq2) = @keys;
            my ($count1, $count2) = @c{@keys};
    
            if (($freq1 == 1 && $count1 == 1) || ($freq2 == 1 && $count2 == 1)) {
                return "YES";
            }
    
            if ((abs($freq1 - $freq2) == 1) && ($count1 == 1 || $count2 == 1)) {
                return "YES";
            }
        }
    
        return "NO";
    }