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

如何统计每根红蜡烛后连续绿蜡烛数量并标注于对应红蜡烛上方

实现红蜡烛后连续绿蜡烛数量统计

核心逻辑

不管用哪种编程语言,核心步骤都是一致的:

  • 遍历蜡烛序列的每个字符
  • 遇到红蜡烛(R)时,从它的下一个位置开始,统计连续出现的绿蜡烛(G)数量
  • 统计截止到遇到非G字符或序列末尾
  • 按R出现的顺序保存统计结果,结果列表中的每个数字对应原序列中对应R的标注值

Python 实现

def count_g_after_r(candle_str):
    result = []
    total = len(candle_str)
    for idx in range(total):
        if candle_str[idx] == 'R':
            g_count = 0
            next_idx = idx + 1
            while next_idx < total and candle_str[next_idx] == 'G':
                g_count += 1
                next_idx += 1
            result.append(g_count)
    return result

# 测试示例
test_candles = "RGGRRGGGGRG"
print(count_g_after_r(test_candles))  # 输出: [2, 0, 4, 1]

JavaScript 实现

function countGAfterR(candleStr) {
    const result = [];
    const total = candleStr.length;
    for (let idx = 0; idx < total; idx++) {
        if (candleStr[idx] === 'R') {
            let gCount = 0;
            let nextIdx = idx + 1;
            while (nextIdx < total && candleStr[nextIdx] === 'G') {
                gCount++;
                nextIdx++;
            }
            result.push(gCount);
        }
    }
    return result;
}

// 测试示例
const testCandles = "RGGRRGGGGRG";
console.log(countGAfterR(testCandles)); // 输出: [2, 0, 4, 1]

内容的提问来源于stack exchange,提问作者sey eeet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 19:57:10