You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 string declaration (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:17:56