gpt4 book ai didi

java - 字符串的最大匹配

转载 作者:搜寻专家 更新时间:2023-10-31 20:22:50 24 4
gpt4 key购买 nike

我正在尝试编写一种方法,该方法将返回与我需要传递给 Web 服务的银行产品相对应的代码。我有一组合格的 generic 产品类型,输入将是一个字符串,它将是数组中任何通用类型的特定类型。让我通过我已有的代码来解释这一点:

public static void main(String[] args) 
{
String[] names = { "Checking", "Savings", "DEMAT", "DEMAT Savings", "Interest Checking" };
String input = "Employee Checking";
int min = Integer.MAX_VALUE;
String maxMatch = null;
for(String name : names)
{
int i = input.indexOf(name);
if(i > -1 && i < min)
{
min = i;
maxMatch = name;
}
}
if(null != maxMatch)
{
System.out.println("Maximum match for " + input + " found at " + maxMatch);
}
}

上面的代码片段尝试对输入执行最大匹配。因此,如果我将“员工兴趣检查”作为输入,我会在“兴趣检查”处获得匹配,而不仅仅是“检查”。

我想知道的是,是否有任何方法可以进一步优化这段代码,或者是否存在这段代码会失败的情况?

最佳答案

如果你保持按字符串长度排序的数组,你可以确定第一个匹配将给出最大匹配

import java.util.Arrays;
import java.util.Comparator;

public class MaxIndex {

private static String[] names = { "Checking", "Savings", "DEMAT", "DEMAT Savings",
"Interest Checking","Savings Interest Checking","My Employee Savings Interest Checking" };

public static void main(String[] args) {

Arrays.sort(names, new Comparator<String>() {

@Override
public int compare(String o1, String o2) {
Integer L1 = o1.length();
return L1.compareTo(o2.length())*-1;
}
});

findMaxMatch("Employee Checking");
findMaxMatch("Employee Savings");
findMaxMatch("Employee Interest Checking");
findMaxMatch("Employee Savings Interest Checking");
findMaxMatch("My Employee Savings Interest Checking");
findMaxMatch("Employee Current");
}

private static void findMaxMatch(String input) {
String maxMatch = maxMatch(input);
if (null != maxMatch) {
System.out.println("Maximum match for '" + input + "' found at '"
+ maxMatch+"'");
}else{
System.out.println("No match for '"+input+"'");
}
}

private static String maxMatch(String input) {
for (String name : names) {
int i = input.indexOf(name);
if (i > -1) {
return name;
}
}
return null;
}

输出

Maximum match for 'Employee Checking' found at 'Checking'
Maximum match for 'Employee Savings' found at 'Savings'
Maximum match for 'Employee Interest Checking' found at 'Interest Checking'
Maximum match for 'Employee Savings Interest Checking' found at 'Savings Interest Checking'
Maximum match for 'My Employee Savings Interest Checking' found at 'My Employee Savings Interest Checking'
No match for 'Employee Current'

关于java - 字符串的最大匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8195664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com