字符串压缩编码实现问题:重复字符超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
currentCharto 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
currentCharandcountfor the new character.
- If it matches
- 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
appendGrouptakes 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 repeatedcounttimes.
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
相关产品推荐
相关产品推荐

