C#实现:查找与样本字符串最长连续匹配子串的列表项
解决发票行项与合同行项的最长连续子串匹配问题
你需要实现的是从合同行项的任意位置查找与发票行项的最长连续匹配子串,而非仅从开头匹配。以下是针对该需求的改进方案:
问题场景回顾
发票行项示例:"145HBK25G"
合同行项列表示例:
"PU125TECHNOAES145HBK2", "PU1212TECHNOAESHS210ZHEA", "PU1219TECHNOAESHS200A5A23", "PU129TECHNOAESBM5614A3A01"
目标是匹配第一项,因为它包含与发票最长的连续匹配子串"145HBK2"。
改进后的实现代码
首先实现一个辅助方法,用于计算两个字符串之间的最长连续公共子串长度:
private static int GetLongestConsecutiveMatchLength(string invoiceStr, string contractStr) { int maxMatchLength = 0; int invoiceLength = invoiceStr.Length; int contractLength = contractStr.Length; // 遍历发票字符串的所有起始位置 for (int invoiceStart = 0; invoiceStart < invoiceLength; invoiceStart++) { // 遍历合同字符串的所有起始位置 for (int contractStart = 0; contractStart < contractLength; contractStart++) { int currentMatch = 0; // 统计从当前起始点开始的连续匹配字符数 while (invoiceStart + currentMatch < invoiceLength && contractStart + currentMatch < contractLength && invoiceStr[invoiceStart + currentMatch] == contractStr[contractStart + currentMatch]) { currentMatch++; } // 更新最长匹配长度 if (currentMatch > maxMatchLength) { maxMatchLength = currentMatch; } } } return maxMatchLength; }
然后在主逻辑中遍历所有合同行项,找到匹配长度最长的项:
// 示例输入 string invoiceLineItem = "145HBK25G"; List<string> contractLineItems = new List<string> { "PU125TECHNOAES145HBK2", "PU1212TECHNOAESHS210ZHEA", "PU1219TECHNOAESHS200A5A23", "PU129TECHNOAESBM5614A3A01" }; int longestMatch = 0; string bestMatchContractItem = null; foreach (var contractItem in contractLineItems) { int currentMatchLength = GetLongestConsecutiveMatchLength(invoiceLineItem, contractItem); if (currentMatchLength > longestMatch) { longestMatch = currentMatchLength; bestMatchContractItem = contractItem; } } // 输出结果 Console.WriteLine($"匹配到的合同行项: {bestMatchContractItem}"); Console.WriteLine($"最长连续匹配长度: {longestMatch}");
代码说明
- 辅助方法
GetLongestConsecutiveMatchLength会检查两个字符串所有可能的起始位置组合,找到最长的连续匹配子串长度,解决了原代码仅从开头匹配的局限。 - 主逻辑遍历所有合同行项,记录匹配长度最大的项,最终得到符合需求的匹配结果。
内容的提问来源于stack exchange,提问作者AJ L
相关产品推荐
相关产品推荐

