forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaxCharacter.php
32 lines (26 loc) · 940 Bytes
/
MaxCharacter.php
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
<?php
/**
* This function returns the character which is repeated maximum number of
* times in the given string.
*
* @param string $string
* @return string
*/
function maxCharacter(string $string)
{
if (empty($string)) {
throw new \Exception('Please pass a non-empty string value');
}
$characterCountTable = []; // A variable to maintain the character counts
$string = strtolower($string); // For case-insensitive checking
$characters = str_split($string); // Splitting the string to a Character Array.
foreach ($characters as $character) {
$currentCharacterCount = 1;
if (isset($characterCountTable[$character])) {
$currentCharacterCount = $characterCountTable[$character] + 1;
}
$characterCountTable[$character] = $currentCharacterCount;
}
arsort($characterCountTable);
return array_keys($characterCountTable)[0];
}