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

Java实现字符串每3个字符首位移至末位,求嵌套循环等替代方案

嵌套for循环实现方案

你现有的实现已经是时间复杂度O(n)的高效方案,如需要嵌套for循环的写法,可以按分组逻辑拆分内外层遍历,外层控制分组起始位置,内层处理单组内的字符偏移逻辑,代码如下:

public String switcheroo(String word) {
    if (word == null || word.length() < 3) {
        return word;
    }
    StringBuilder sb = new StringBuilder(word.length());
    int totalLen = word.length();
    // 外层循环:遍历所有分组的起始下标
    for (int groupStart = 0; groupStart < totalLen; groupStart += 3) {
        int groupLen = Math.min(3, totalLen - groupStart);
        // 内层循环:处理当前分组的字符
        for (int offset = 0; offset < groupLen; offset++) {
            if (groupLen < 3) {
                // 不足3个字符直接按原顺序追加
                sb.append(word.charAt(groupStart + offset));
                continue;
            }
            // 3字符组:先输出原第2、3位,最后输出原第1位
            if (offset == 0) {
                sb.append(word.charAt(groupStart + 1));
            } else if (offset == 1) {
                sb.append(word.charAt(groupStart + 2));
            } else {
                sb.append(word.charAt(groupStart));
            }
        }
    }
    return sb.toString();
}

其他可选实现思路

正则替换方案

如果不需要极致性能,规则固定的场景下可以用正则匹配替换,代码更简洁:

public String switcheroo(String word) {
    if (word == null || word.length() < 3) {
        return word;
    }
    // 匹配每3个连续字符,将第1位移到组末尾
    return word.replaceAll("(.{3})", "$2$3$1");
}

不同方案对比

  • 嵌套for循环:逻辑灵活,后续调整分组长度、组内偏移规则时修改成本低
  • 原生substring方案(你原有实现):性能最优,适合处理超长字符串场景
  • 正则方案:代码最简洁,适合规则固定的轻量使用场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:18:03