Vru*_*ank 5 java string optimization
我正在尝试编写一个方法,它将返回与我需要传递给Web服务的银行产品相对应的代码.我有一系列符合条件的通用类型的产品,输入将是一个字符串,它将是数组中任何泛型类型的特定类型.让我通过我已有的代码解释一下:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码片段尝试为输入执行最大匹配.因此,如果我将"员工兴趣检查"作为输入,我会在"兴趣检查"中获得匹配而不仅仅是"正在检查".
我想知道的是,是否有任何方法可以进一步优化此代码段,或者是否存在此代码失败的情况?
如果您按字符串长度保留排序数组,则可以确定第一个匹配将给出最大匹配
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;
}
Run Code Online (Sandbox Code Playgroud)
}
输出
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'
Run Code Online (Sandbox Code Playgroud)