[LinkedIn] Word Distance Finder (Find distance in dictionary)

来源:互联网 发布:sql 计算查询结果合计 编辑:程序博客网 时间:2024/05/19 20:49

Example:

WordDistanceFinder finder = new WordDistanceFinder(Arrays.asList(“the”, “quick”, “brown”, “fox”, “quick”));

assert(finder.distance(“fox”,”the”) == 3);

assert(finder.distance(“quick”, “fox”) == 1);

/**Solution: go step by step, keep updating the max distance**/String targetString = "quick";String targetString2 = "fox";int index1 = -1, index2 = -1;int minDistance = Integer.MAX_VALUE, tempDistance = 0;for (int x = 0; x < strings.length; x++) {    if (strings[x].equals(targetString)) {        index1 = x;    }    if (strings[x].equals(targetString2)) {        index2 = x;    }    if (index1 != -1 && index2 != -1) { // both words have to be found        tempDistance = (int) Math.abs(index2 - index1);        if (tempDistance < minDistance) {            minDistance = tempDistance;        }    }}System.out.println("Distance:\t" + minDistance);
0 0
原创粉丝点击