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

字符串压缩编码实现问题:重复字符超2次才替换计数

Solution for General String Encryption with Repeat Rules

Got it, let's fix this to handle any string instead of just the character 't'! Here's a complete Swift solution that follows your exact conversion rules:

The Working Code

func encrypt(_ str: String) -> String {
    guard !str.isEmpty else { return "" }
    
    var result = ""
    var currentChar = str.first!
    var count = 1
    
    // Loop through every character after the first one
    for char in str.dropFirst() {
        if char == currentChar {
            count += 1
        } else {
            // Add the current repeated group to our result
            appendGroup(to: &result, char: currentChar, count: count)
            // Reset for the new character we just found
            currentChar = char
            count = 1
        }
    }
    
    // Don't forget to add the last group of characters
    appendGroup(to: &result, char: currentChar, count: count)
    
    return result
}

// Helper function to handle how we add a group of repeated characters
private func appendGroup(to result: inout String, char: Character, count: Int) {
    if count > 2 {
        result.append("\(char)\(count)")
    } else {
        result.append(String(repeating: char, count: count))
    }
}

How It Works

Let's walk through the logic so you understand what's happening:

  • We start by checking if the input string is empty (no need to do anything if it is).
  • We initialize currentChar to the first character of the string and set its starting count to 1.
  • For each subsequent character:
    • If it matches currentChar, we increment the count of consecutive repeats.
    • If it doesn't match, we process the current group of repeated characters using our helper function, then reset currentChar and count for the new character.
  • After the loop ends, we have to process the last group of characters (since the loop doesn't handle it when it reaches the end of the string).
  • The helper function appendGroup takes care of the rule: if a character repeats more than 2 times, we add [character][count] to the result; otherwise, we just add the character repeated count times.

Test Cases (Matches Your Requirements)

  • encrypt("atttbcdddd") → returns "at3bcd4"
  • encrypt("aa") → returns "aa"
  • encrypt("aaa") → returns "a3"
  • encrypt("aahhhgggg") → returns "aah3g4"

This replaces your original code that only handled the character 't' with a flexible solution that works for any input string while strictly following your conversion rules.

内容的提问来源于stack exchange,提问作者Stanislav Marynych

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:45:38