perl - minimum number of character deletions (of both) required to turn these strings into anagrams? -
two strings given,how many minimum number of character deletions (of both) required turn these strings anagrams. constraint: need use single hash
aaabbc abc
output - 3 ( 2 , 1 b)
i able achieve using 2 hashes , tried below solution using 1 hash -
my $str1 = 'aaabbc'; $str2 = 'abc'; %h; map{$h{$_}++} sort(//,$str1); map{$h{$_}++} sort(//,$str2); $c = 0; foreach (keys(%h)) { if($h{$_} == 1) { $c++; } } print "$c\n"; it fail in many case ('xxx', 'yyy'). suggestions?
to use single hash (smells homework) increment count characters in first string , decrement characters in second string. equal numbers of same character cancel out. non-zero values remain magnitude of difference, take absolute value when tallying total number of differences.
my $str1 = 'aaabbc'; $str2 = 'abc'; %h; $c; $h{$_}++ foreach split //, $str1; $h{$_}-- foreach split //, $str2; $c += abs($_) foreach values %h; print $c;
Comments
Post a Comment