如何统计每根红蜡烛后连续绿蜡烛数量并标注于对应红蜡烛上方
实现红蜡烛后连续绿蜡烛数量统计
核心逻辑
不管用哪种编程语言,核心步骤都是一致的:
- 遍历蜡烛序列的每个字符
- 遇到红蜡烛(
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
相关产品推荐
相关产品推荐

