如何移除字符串压缩Java代码中的重复逻辑(不新增方法)
移除字符串压缩代码中的重复逻辑
功能说明
这段代码实现字符串压缩功能,将字符串中相邻重复字符替换为对应的计数。示例如下:
输入:
aaabbccdsa
预期输出:
a3b2c2dsa
原代码可正常运行,但存在两处完全重复的if条件逻辑,且要求不新增单独方法来消除重复。
原代码
public class Solution { public static String getCompressedString(String str) { String result = ""; char anch = str.charAt(0); int count = 0; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == anch) { count++; } else { if (count == 1) { // 重复逻辑开始 result += anch; } else { result += anch + Integer.toString(count); } // 重复逻辑结束 anch = ch; count = 1; } if (i == str.length() - 1) { if (count == 1) { // 重复逻辑开始 result += anch; } else { result += anch + Integer.toString(count); } // 重复逻辑结束 } } return result; } }
重复的逻辑块:
if (count == 1) { result += anch; } else { result += anch + Integer.toString(count); }
优化后的代码
调整循环逻辑,将重复的拼接逻辑只保留一份,同时优化字符串拼接效率(原String+=会频繁创建新对象,改用StringBuilder):
public class Solution { public static String getCompressedString(String str) { // 空字符串判断,避免索引越界 if (str.isEmpty()) { return ""; } StringBuilder result = new StringBuilder(); char anch = str.charAt(0); int count = 1; // 从第2个字符开始遍历 for (int i = 1; i < str.length(); i++) { char ch = str.charAt(i); if (ch == anch) { count++; } else { // 处理前一组重复字符,只写一次拼接逻辑 result.append(anch); if (count > 1) { result.append(count); } // 更新锚点和计数 anch = ch; count = 1; } } // 处理最后一组未拼接的字符 result.append(anch); if (count > 1) { result.append(count); } return result.toString(); } }
优化说明
- 调整循环起始位置为
i=1,初始化count=1,避免原代码中count从0开始的额外判断 - 仅在字符切换时处理前一组重复字符的拼接逻辑,循环结束后单独处理最后一组字符,彻底消除重复代码
- 用
StringBuilder替代String拼接,大幅提升大字符串处理时的效率
内容的提问来源于stack exchange,提问作者aekit
相关产品推荐
相关产品推荐

