C#判断输入字符串能否组成有效英文单词的代码问题排查
乱序字符串匹配单词代码问题排查
需求说明:判断输入字符串是否可通过字符重排组成有效英文单词,本次实现不调用第三方词典API,采用硬编码字符串数组作为模拟词典,要求匹配到对应词条时输出正确的词典单词内容。
现有代码问题汇总
- 词典字符统计逻辑错误:
arrayDict一次性统计了词典所有单词的字符总数,没有按单个单词独立统计字符计数,直接导致后续匹配的计数基准完全错误。 - 匹配判断逻辑失效:
- 逐字符遍历单词时,每检查一个字符就触发一次结果输出,会导致同一个单词被重复打印多次,同时刷出大量无意义的"Doesn't match"提示
- 计数判断使用
inputDict.ContainsValue(arrayDict[array[j][k]])逻辑完全错误,该方法仅检查字典中是否存在任意键对应的值等于传入数值,并非校验当前字符在输入中的计数和单词中的计数是否一致 - 长度校验放在逐字符循环内部,没有提前筛除长度不匹配的单词,增加无效计算
- 方法返回值无意义:
Jumble方法始终返回空字符串,没有实际承载匹配结果。
修正后实现代码
public class Program { public static string Jumble(string input) { // 模拟词典 string[] wordList = { "abstract", "car", "flight" }; // 预处理输入字符串的字符计数 Dictionary<char, int> inputCharCount = new Dictionary<char, int>(); foreach (char c in input) { if (inputCharCount.ContainsKey(c)) inputCharCount[c]++; else inputCharCount[c] = 1; } // 遍历每个词典单词匹配 foreach (string word in wordList) { // 长度不一致直接跳过,不可能匹配 if (word.Length != input.Length) continue; // 统计当前单词的字符计数 Dictionary<char, int> wordCharCount = new Dictionary<char, int>(); foreach (char c in word) { if (wordCharCount.ContainsKey(c)) wordCharCount[c]++; else wordCharCount[c] = 1; } // 校验字符计数是否完全一致 bool isMatch = true; foreach (var kv in wordCharCount) { if (!inputCharCount.ContainsKey(kv.Key) || inputCharCount[kv.Key] != kv.Value) { isMatch = false; break; } } if (isMatch) { Console.WriteLine(word); return word; } } // 所有词都不匹配 Console.WriteLine("Doesn't match"); return ""; } static void Main(string[] args) { string input = "tracabst"; Jumble(input); Console.ReadLine(); } }
代码验证说明:传入示例输入tracabst时,会正确匹配输出abstract,符合预期。
内容的提问来源于stack exchange,提问作者Roma Sahoo
相关产品推荐
相关产品推荐

