JavaScript中字符串多字符出现次数相同时,如何返回所有高频字符?
Fixing the maxChar Function to Handle Multiple Highest-Frequency Characters
Let's sort out this issue where your current maxChar function only returns one character even when multiple characters share the highest occurrence count. For input like "aabbc", we want to highlight both a and b since they both appear 2 times, not just the last one the loop stumbles on.
Step-by-Step Breakdown & Solution
First, let's spot the problem in the original code: when iterating through the character count object, it replaces maxChar every time it finds a character with a count >= the current max. This means only the last matching character gets kept, instead of gathering all characters that hit the highest count.
Here's the revised code that fixes this:
function maxChar(str) { // Step 1: Count how many times each character appears let charCounts = {}; for (let char of str) { // Shorter way to increment counts (handles undefined initial values) charCounts[char] = (charCounts[char] || 0) + 1; } // Step 2: Figure out the highest occurrence count let maxCount = Math.max(...Object.values(charCounts)); // Step 3: Gather all characters that have this max count let topChars = Object.keys(charCounts).filter(char => charCounts[char] === maxCount); // Step 4: Format the output to handle single or multiple characters let output; if (topChars.length === 1) { output = `${topChars[0]} appear ${maxCount} times`; } else { // Join multiple characters with " & " — adjust to ", " + " & " for 3+ chars if you prefer output = `${topChars.join(" & ")} appear ${maxCount} times`; } console.log(output); } // Test the function with different cases maxChar("aabbc"); // Output: "a & b appear 2 times" maxChar("aaabbbcc"); // Output: "a & b appear 3 times" maxChar("aaaa"); // Output: "a appear 4 times" maxChar("abcde"); // Output: "a & b & c & d & e appear 1 times"
Key Improvements
- Get the max count upfront: Using
Math.max(...Object.values(charCounts))lets us grab the highest occurrence number first, instead of tracking it while looping. - Collect all top characters: We filter the character keys to pull every character that matches the max count, not just the last one.
- Flexible output formatting: Automatically adjusts whether it shows a single character or multiple ones joined cleanly.
内容的提问来源于stack exchange,提问作者Vickram
相关产品推荐
相关产品推荐

