3541. Find Most Frequent Vowel and Consonant #2168
-
Topics: You are given a string Your task is to:
Return the sum of the two frequencies. Note: If multiple vowels or consonants have the same maximum frequency, you may choose any one of them. If there are no vowels or no consonants in the string, consider their frequency as 0. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the sum of the maximum frequency of a vowel and the maximum frequency of a consonant in a given string. The solution involves counting the occurrences of each character, categorizing them as vowels or consonants, and then determining the highest frequency in each category. Approach
Let's implement this solution in PHP: 3541. Find Most Frequent Vowel and Consonant <?php
/**
* @param String $s
* @return Integer
*/
function maxFreqSum($s) {
$vowels = array('a', 'e', 'i', 'o', 'u');
$freq = array();
$n = strlen($s);
for ($i = 0; $i < $n; $i++) {
$char = $s[$i];
if (!isset($freq[$char])) {
$freq[$char] = 0;
}
$freq[$char]++;
}
$maxVowel = 0;
$maxConsonant = 0;
foreach ($freq as $char => $count) {
if (in_array($char, $vowels)) {
if ($count > $maxVowel) {
$maxVowel = $count;
}
} else {
if ($count > $maxConsonant) {
$maxConsonant = $count;
}
}
}
return $maxVowel + $maxConsonant;
}
// Test cases
echo maxFreqSum("successes") . "\n"; // Output: 6
echo maxFreqSum("aeiaeia") . "\n"; // Output: 3
echo maxFreqSum("zzz") . "\n"; // Output: 3
echo maxFreqSum("a") . "\n"; // Output: 1
?> Explanation:
This approach efficiently categorizes and counts the characters, ensuring optimal performance even for the upper constraint of string length (100 characters). The solution is straightforward and leverages basic array operations to achieve the desired result. |
Beta Was this translation helpful? Give feedback.
We need to find the sum of the maximum frequency of a vowel and the maximum frequency of a consonant in a given string. The solution involves counting the occurrences of each character, categorizing them as vowels or consonants, and then determining the highest frequency in each category.
Approach