C#等长字符串字符唯一映射判定问题求助
问题排查与代码修正
现有代码核心问题
- 长度不等校验逻辑不完整:检测到两个字符串长度不一致后没有提前终止后续逻辑,无效代码仍会执行后续循环
- 映射存储逻辑失效:你定义的
firstPhraseChars和secondPhraseChars数组初始化后默认值为\0,判断firstPhrase[i] == firstPhraseChars[i]的条件仅当输入字符为\0才会触发,正常输入场景下永远不会执行映射存储的代码 - 映射唯一性判断逻辑完全错误:嵌套的j循环逻辑混乱,反复覆盖
result的值,没有实现双向唯一性校验:合法映射需要满足两个规则:- 第一个字符串中同一个字符,必须对应第二个字符串中同一个字符
- 第二个字符串中同一个字符,也不能对应第一个字符串中不同的字符,避免多对一的不唯一映射
- 输出逻辑不符合要求:示例要求输出去重后的映射关系,而不是每个位置的对应关系
修正后代码
using System; namespace UniqueStrings { class Program { static void Main(string[] args) { string firstPhrase = Console.ReadLine(); string secondPhrase = Console.ReadLine(); bool isMappingValid = true; // 首先校验长度是否一致 if (firstPhrase.Length != secondPhrase.Length) { isMappingValid = false; Console.WriteLine(isMappingValid); Console.Read(); return; } int length = firstPhrase.Length; // 用两个数组存储已经记录的映射对 char[] sourceChars = new char[length]; char[] targetChars = new char[length]; int mappingCount = 0; // 遍历每个位置校验映射 for (int i = 0; i < length; i++) { char currentSource = firstPhrase[i]; char currentTarget = secondPhrase[i]; bool found = false; // 查找当前源字符是否已经存在映射 for (int j = 0; j < mappingCount; j++) { if (sourceChars[j] == currentSource) { found = true; // 已有映射和当前目标字符不一致,映射非法 if (targetChars[j] != currentTarget) { isMappingValid = false; break; } } } if (!isMappingValid) break; // 如果源字符没找到映射,校验目标字符是否已经被其他源字符映射 if (!found) { for (int j = 0; j < mappingCount; j++) { if (targetChars[j] == currentTarget) { isMappingValid = false; break; } } if (!isMappingValid) break; // 双向都没找到重复,添加新映射 sourceChars[mappingCount] = currentSource; targetChars[mappingCount] = currentTarget; mappingCount++; } } // 输出结果 Console.WriteLine(isMappingValid); if (isMappingValid) { for (int i = 0; i < mappingCount; i++) { Console.WriteLine($"{sourceChars[i]} => {targetChars[i]}"); } } Console.Read(); } } }
修正说明
- 增加长度校验后的提前返回逻辑,避免无效运算
- 调整映射校验逻辑同时满足双向唯一性要求,一对多、多对一的情况都会被判定为非法
- 映射数组仅存储每个字符的唯一对应关系,输出结果和示例要求完全匹配
- 没有使用Dictionary、List、LINQ等被禁止的功能,仅使用System命名空间下的基础数组、循环等功能
内容的提问来源于stack exchange,提问作者AndrewM
相关产品推荐
相关产品推荐

