如何修正RebelEncoding函数压缩编码结果,使其符合无标点的预期输出?
问题分析
当前代码的问题在于将空格视为普通字符进行压缩,导致单个空格被输出为1 ,而期望输出中直接保留空格;同时,原代码在处理标点后的字符时逻辑正确,但未对空格做特殊处理,最终导致输出出现多余的数字(如311实际是31+1 的拼接效果)。
另外,原代码存在一个潜在问题:如果输入字符串以标点开头,会将标点字符加入结果中,违反了返回值不得包含标点的要求。
修正后的代码
static string RebelEncoding(string str) { if (str == null || str == "") { return str; } StringBuilder sb = new StringBuilder(); // 跳过开头所有标点,找到第一个有效字符 int startIndex = 0; while (startIndex < str.Length && Char.IsPunctuation(str[startIndex])) { startIndex++; } // 全是标点的情况,返回空字符串 if (startIndex >= str.Length) { return ""; } char prevChar = str[startIndex]; int count = 1; for (int i = startIndex + 1; i < str.Length; i++) { if (!Char.IsPunctuation(str[i])) { char currentChar = str[i]; if (currentChar == prevChar) { count++; } else { // 空格特殊处理:直接输出,不添加计数 if (prevChar == ' ') { sb.Append(prevChar); } else { sb.Append(count); sb.Append(prevChar); } prevChar = currentChar; count = 1; } } } // 处理最后一组字符 if (prevChar == ' ') { sb.Append(prevChar); } else { sb.Append(count); sb.Append(prevChar); } return sb.ToString(); } static void Main(string[] args) { string results = RebelEncoding("Squad Beta-111 attack!"); Console.WriteLine(results); Console.ReadLine(); }
修改说明
- 跳过开头标点:添加逻辑找到第一个非标点字符作为压缩起始点,避免将标点加入结果。
- 空格特殊处理:在输出字符时,判断如果是空格则直接输出,不添加前面的计数,解决了原输出中
1的问题。 - 移除冗余逻辑:原代码中判断结果长度与原字符串长度的分支无实际意义,直接移除,简化代码。
测试该代码处理输入"Squad Beta-111 attack!"时,将输出期望的1S1q1u1a1d 1B1e1t1a31 1a2t1a1c1k。
内容的提问来源于stack exchange,提问作者Mokoena Föçê
相关产品推荐
相关产品推荐

