August 24, 2010
Find the most repeated character in a string
Most repeated character string
Given a string of characters find the character that is repeated the most.
Solution
This is almost the same as the First None Repeating Char problem. We are going to borrow the same code however we will slightly modify it. The only code that we need to add is calculating the maximum while hashing the characters. We can also calculate the maximum in a separate loop right after we populate the hash table but that is not necessary because we can do it in one step as I mentioned earlier.
Code
Here is code for repeated characters in perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# Input string $mystr = "baby"; # Call function print "Character repeated the most is (" . &MaxRepeated($mystr); # Function receives input string sub MaxRepeated { # Input parameter my ($str) = @_; # Get characters @chars = split ('', $str); # Hash data structure %H = (); # Initialize max $max = 0; # Add the chars to the hash table foreach $char (@chars) { # char is used as the key # and the value is the count # of that char in the string # Repeated chars hash to the # same position $H{$char}++; # Update max and save character if ($H{$char} > $max) { $max = $H{$char}; $res = $char; } } return $res . ") with count " . $max; } |
Thanks for reading. For comments and feedback, please use the comments section below.