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

如何修改Java代码以适配多字符串的双向替换(压缩/解压)需求?

解决方案

一、修复并增强 compressWord 方法

原方法仅处理第一个目标子串,核心问题是固定依赖targetWord[0]未遍历所有规则。我们需要在每个位置检查所有可能的子串,且优先匹配长度更长的子串(避免短子串先匹配导致长子串被忽略,比如若存在"tion",需先匹配"ion"而非"re")。

修改后的代码:

public static String compressWord(String word) {
    if (word == null) {
        throw new IllegalArgumentException("Null word");
    }

    // 按子串长度降序排列替换规则,确保长串优先匹配
    String[][] replacements = {
        {"the", "&"},
        {"ion", "#"},
        {"ing", "@"},
        {"tis", "%"},
        {"men", "+"},
        {"an", "~"},
        {"re", "$"}
    };

    StringBuilder sb = new StringBuilder();
    int i = 0;
    int wordLength = word.length();

    while (i < wordLength) {
        boolean foundMatch = false;
        // 遍历所有规则,寻找当前位置的匹配子串
        for (String[] pair : replacements) {
            String target = pair[0];
            String replacement = pair[1];
            int targetLen = target.length();

            // 检查当前位置是否能容纳目标子串且匹配
            if (i + targetLen <= wordLength && word.substring(i, i + targetLen).equals(target)) {
                sb.append(replacement);
                i += targetLen;
                foundMatch = true;
                break; // 找到匹配后跳转至下一个待处理位置
            }
        }
        // 无匹配时,直接保留当前字符并移动指针
        if (!foundMatch) {
            sb.append(word.charAt(i));
            i++;
        }
    }

    return sb.toString();
}

关键优化点:

  • 将替换规则整合为二维数组,便于维护和遍历
  • 按子串长度降序排序,避免短串优先匹配导致的逻辑错误
  • 逐位置检查所有规则,匹配则替换并跳过对应长度,否则保留原字符

二、实现 decompressWord 方法

解压逻辑核心是将替换符号还原为对应原串,使用Map存储映射可提升查找效率。

代码实现:

import java.util.HashMap;
import java.util.Map;

public static String decompressWord(String word) {
    if (word == null) {
        throw new IllegalArgumentException("Null word");
    }

    // 建立替换字符到原串的映射表
    Map<Character, String> decompressMap = new HashMap<>();
    decompressMap.put('&', "the");
    decompressMap.put('~', "an");
    decompressMap.put('#', "ion");
    decompressMap.put('@', "ing");
    decompressMap.put('%', "tis");
    decompressMap.put('+', "men");
    decompressMap.put('$', "re");

    StringBuilder sb = new StringBuilder();
    int i = 0;
    int wordLength = word.length();

    while (i < wordLength) {
        char currentChar = word.charAt(i);
        // 检查当前字符是否为替换符号,是则还原,否则直接保留
        if (decompressMap.containsKey(currentChar)) {
            sb.append(decompressMap.get(currentChar));
        } else {
            sb.append(currentChar);
        }
        i++;
    }

    return sb.toString();
}

说明:

  • HashMap的O(1)查找效率比遍历数组更高
  • 逐字符处理,逻辑清晰,无复杂分支

三、验证示例

  • 压缩:输入"Thank you" → 输出"Th~k you"(匹配"an"替换为"~")
  • 解压:输入"Th~k you" → 输出"Thank you"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 16:13:15