JavaScript新手求助:统计字符串中最长连续相同字符(非总出现次数)
How to Count the Longest Consecutive Repeating Character in a String
Hey there! I see you're diving into JavaScript and hit a snag with counting the longest run of consecutive identical characters—let's work through this together. Your current code counts all instances of 'a' in the string, but we need to track consecutive occurrences instead.
Step-by-Step Approach
Here's a clear way to tackle this problem:
- Initialize variables to track the current streak length, the longest streak found, and the character associated with that longest streak.
- Loop through each character in your lowercase string, comparing it to the previous character.
- Extend the current streak if the character matches the previous one; reset the streak if it doesn't.
- Whenever the current streak surpasses the longest streak we've recorded, update our max values.
Complete Working Code
Replace your existing writeInConsole function with this updated version:
var string = "assssssadaaaAAAasadaaab"; string = string.toLowerCase(); // Avoid redeclaring the same variable here! function writeInConsole() { // Handle edge case: empty string if (string.length === 0) { console.log("(0, )"); return; } let maxCount = 1; let currentCount = 1; let resultChar = string[0]; let currentChar = string[0]; for (let i = 1; i < string.length; i++) { if (string[i] === currentChar) { // Same as the previous character—extend the current streak currentCount++; } else { // New character—reset the current streak currentChar = string[i]; currentCount = 1; } // Update max values if current streak is longer than the previous max if (currentCount > maxCount) { maxCount = currentCount; resultChar = currentChar; } } // Output the result in the required format console.log(`(${maxCount}, ${resultChar})`); } writeInConsole(); // This will log (7, a) as expected!
Key Details to Note:
- We removed the duplicate
var stringdeclaration (redeclaring variables in the same scope is poor practice and can cause bugs). - The loop starts at index 1 because we already initialized our tracking variables with the first character of the string.
- For each character, we either extend the current streak or start a new one, then check if we've found a longer streak to update our result.
- This solution runs in O(n) time (we only loop through the string once), making it efficient even for longer strings.
内容的提问来源于stack exchange,提问作者Karol Pośpiech
相关产品推荐
相关产品推荐

