【发布时间】:2015-05-01 23:49:46
【问题描述】:
我的问题是我有一个名为 N 的数组中的工作列表,例如“会计”、“工料测量员”。我想接受诸如“总会计师”之类的输入并更改为会计师。
我想出的方法是:
- 小写 - 输入和数组
- 去掉空白处
- 将输入中的每个字符与 N 中存储的作业中的每个字符进行比较。
- q ,其中 q = sameChar/当前作业的长度
- 将标准化作业名称及其对应的 q 值存储在哈希表中
我的问题是我无法比较两个字符串之间的字符。谁能指出我做错了什么。提前致谢
编辑 - 尝试使用 tucuxi 提出的方法,但尝试执行时出现错误。
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.util.HashMap.add
at Normaliser.normalise(Normaliser.java:41)
at Normaliser.main(Normaliser.java:49)
Java Result: 1
import java.lang.*;
import java.util.HashMap;
public class Normaliser {
public static int distance(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
// i == 0
int [] costs = new int [b.length() + 1];
for (int j = 0; j < costs.length; j++)
costs[j] = j;
for (int i = 1; i <= a.length(); i++) {
// j == 0; nw = lev(i - 1, j)
costs[0] = i;
int nw = i - 1;
for (int j = 1; j <= b.length(); j++) {
int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);
nw = costs[j];
costs[j] = cj;
}
}
return costs[b.length()];
}
public static HashMap<String, Integer> normalise(String jobTitle, String[] normalTitles) {
HashMap<String, Integer> normalized = new HashMap<String, Integer>();
for (String n : normalTitles) {
normalized.add(n, n.length() - distance(normalTitles, n));
}
return normalized;
}
public static void main(String[] args){
String[] normalTitles = new String[]{"Lawyer", "Engineer", "Accountant"};
HashMap<String, Integer> qs = normalise("Process Engineer", normalTitles);
for (String n : normalTitles) {
System.out.println("job: " + n + " q: " + qs.get(n));
}
}
}
【问题讨论】:
-
我不确定你的代码应该实现什么。如果有任何重复,
jobs.put(N[i], q)将用新值覆盖旧值。此外,由于 normalizer 方法没有输出并且没有触及类属性,所以在调用结束时所有计算都将丢失。您能否编辑您的帖子以显示预期的输入和输出,例如 jt = "Accountant"? -
我要做的是将 q 的值与其相应的作业一起存储。然后我将遍历哈希表并输出具有最高 q 值的作业。
-
那么您最好使用“编辑距离”而不是“相同位置的相同字母”指标。示例:“着色专家”与“着色专家”——编辑距离为 1,但只有 4 个字母共享位置。
标签: java arrays char hashtable