【问题标题】:Java : Get the most similar stringJava:获取最相似的字符串
【发布时间】:2013-08-18 13:29:07
【问题描述】:

需要你的另一个提示:

我有一个包含系统路径的列表:

C:\System\local\something\anything 
C:\System\local\anywhere\somewhere
C:\System\local\
C:\System\
C:\something\somewhere 

我的参考路径是:

C:\System\local\test\anything\

现在我正在寻找最相似的系统路径,结果应该是

Result from the list :
C:\System\local\

那该怎么办?

【问题讨论】:

标签: java


【解决方案1】:

一个可能的解决方案:

循环遍历您的路径列表,将它们拆分为反斜杠字符,然后遍历生成数组的每个值。查看它与参考路径的值相等的时间,并相应地给它们打分。我的例子有点粗糙,但你可以做相应的调整。

public class PathScore {
    public String Path;
    public int Score;
}

public class Systempaths {
    public static void main(String[] args) {
        new Systempaths();
    }

    public Systempaths() {
        String[] paths = new String[5];
        paths[0] = "C:\\System\\local\\something\\anything";
        paths[1] = "C:\\System\\local\\anywhere\\somewhere";
        paths[2] = "C:\\System\\local";
        paths[3] = "C:\\System\\";
        paths[4] = "C:\\something\\somewhere";

        String ref = "C:\\System\\local\\test\\anything";
        String[] reference = ref.split("\\\\");

        List<PathScore> scores = new ArrayList<>();

        for (String s : paths) {
            String[] exploded = s.split("\\\\");
            PathScore current = new PathScore();
            current.Path = s;
            for (int i = 0; i < exploded.length; i++) {
                if (exploded[i].equals(reference[i])) {
                    current.Score = i + 1;
                } else {
                    // Punishment for paths that exceed the reference path (1)
                    current.Score = i - 1;
                    break;
                }
            }

            scores.add(current);
        }

        for (PathScore ps : scores) {
            System.out.printf("%s:\t%d\n", ps.Path, ps.Score);
        }
    }
}

输出:

C:\System\local\something\anything: 2
C:\System\local\anywhere\somewhere: 2
C:\System\local:    3
C:\System\: 2
C:\something\somewhere: 0

(1): 我对过于具体且超出参考路径 ("C:\System\local\test\anything") 允许的路径(如 C:\System\local\something\anything)添加了一个小惩罚。

【讨论】:

  • 谢谢,删除斜线和计分计数器为我做了!
【解决方案2】:

因为你有一个预定义的系统路径列表,现在你有一个参考路径,你需要从列表中找出最相似的系统路径,我的看法是参考路径和反对之间的匹配系统路径列表中的每个项目。基于正则表达式的比较会更容易。

【讨论】:

    【解决方案3】:

    您的示例实际上表明答案是给定路径开始的最长系统路径。这可以计算如下:

    String[] systemPaths = ...
    String path = ...
    String bestMatch = null;
    for (String candidate : systemPaths) {
        if (path.startsWith(candidate) && 
            (bestMatch == null || bestMatch.length() < candidate.length())) {
            bestMatch = candidate;
        }
    }
    

    这假定系统路径都以文件分隔符结尾,并且您希望区分大小写。如果没有,调整应该很明显。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 2010-10-31
      相关资源
      最近更新 更多