Java基于自定义字符集的单词编码顺序问题求助
问题分析与解决方案
你的代码逻辑顺序搞反了:外层遍历自定义字符集,内层遍历输入字符,这会导致先收集所有匹配字符集第一个字符的输入内容,再收集第二个的,自然打乱了原输入的顺序。要保留原顺序,必须按输入字符串的顺序逐个处理每个字符,找到它在CHARACTERS_SPACE中的索引(也就是你要的对应数字)。
基础修正版本
这个版本逻辑简单直接,适合理解:
public static final char[] CHARACTERS_SPACE = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' '}; public static void codificate(String msg) { // 统一转大写,匹配字符集的大小写规则 String upperMsg = msg.toUpperCase(); List<Integer> encodedNumbers = new ArrayList<>(); // 按输入顺序遍历每个字符 for (char c : upperMsg.toCharArray()) { // 查找当前字符在自定义字符集中的索引 for (int i = 0; i < CHARACTERS_SPACE.length; i++) { if (CHARACTERS_SPACE[i] == c) { encodedNumbers.add(i); break; // 找到匹配后立即跳出循环,避免无效遍历 } } } // 输出最终编码结果 System.out.println(encodedNumbers.toString()); }
输入"acbd"时,转大写为"ACBD",对应索引是0,2,1,3,输出结果为[0, 2, 1, 3],完美保留原顺序。
性能优化版本
如果需要处理较长的输入字符串,建议提前把字符集转为HashMap映射,将字符查找的时间复杂度从O(n)降到O(1):
public static final char[] CHARACTERS_SPACE = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' '}; // 静态初始化字符到索引的映射,只执行一次 private static final Map<Character, Integer> CHAR_INDEX_MAP = new HashMap<>(); static { for (int i = 0; i < CHARACTERS_SPACE.length; i++) { CHAR_INDEX_MAP.put(CHARACTERS_SPACE[i], i); } } public static void codificate(String msg) { String upperMsg = msg.toUpperCase(); List<Integer> encodedNumbers = new ArrayList<>(); for (char c : upperMsg.toCharArray()) { Integer index = CHAR_INDEX_MAP.get(c); if (index != null) { encodedNumbers.add(index); } else { // 可根据需求处理不在字符集中的字符,比如打印提示或抛出异常 System.err.println("警告:字符 '" + c + "' 不在自定义字符集中,已跳过"); } } System.out.println(encodedNumbers.toString()); }
内容的提问来源于stack exchange,提问作者trueeh
相关产品推荐
相关产品推荐

