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

如何用JavaScript实现连续重复字符的文本压缩函数?

How to Implement a Run-Length Encoding Function for Text Compression

Hey Paulius, I see where you're stuck here—your current code is counting the total occurrences of each character across the entire string, but what we need is run-length encoding (counting consecutive repeated characters instead). Let's fix that step by step.

Why Your Current Approach Isn't Working

The dictionary output {a: 3, v: 3, f: 3, d: 1} counts how many times each character appears in total. But in your example input "aaavvvfdff", the f appears in two separate consecutive groups: once alone, then twice at the end. We need to capture those separate groups instead of lumping them together.

The Correct Approach: Track Consecutive Characters

Here's a straightforward way to build the function you need:

  1. Handle edge cases first (like empty input).
  2. Initialize variables to track the current character we're counting and how many times it's repeated consecutively.
  3. Iterate through the rest of the string, updating the count when we hit the same character, or saving the current group and switching to a new character when we hit something different.
  4. Don't forget to add the last group of characters after the loop finishes!

Working Code Example

def compress_text(x):
    # Return empty string if input is empty
    if not x:
        return ""
    
    # Initialize tracking variables and result list
    result = []
    current_char = x[0]
    count = 1
    
    # Iterate from the second character onwards
    for char in x[1:]:
        if char == current_char:
            # Same character as current, increment count
            count += 1
        else:
            # Different character: save the current group and reset tracking
            result.append(f"{current_char}{count}")
            current_char = char
            count = 1
    
    # Add the final group (since the loop ends before processing it)
    result.append(f"{current_char}{count}")
    
    # Join all groups into a single string and return
    return ''.join(result)

# Test with your example input
print(compress_text("aaavvvfdff"))  # Output: "a3v3f1d1f2"

Key Notes About This Code

  • Using a list (result) to collect each character-count pair is more efficient than concatenating strings directly (since strings in Python are immutable, repeated concatenation creates unnecessary copies).
  • We explicitly handle empty input to avoid index errors when trying to access x[0].
  • After the loop ends, we have to add the last set of characters because the loop only saves groups when it hits a new character—there's no "new character" trigger for the final group.

This will give you exactly the output you're looking for, tracking consecutive repeats instead of total character counts.

内容的提问来源于stack exchange,提问作者User Paulius

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:37:43