如何用JavaScript实现连续重复字符的文本压缩函数?
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:
- Handle edge cases first (like empty input).
- Initialize variables to track the current character we're counting and how many times it's repeated consecutively.
- 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.
- 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

