Problems with Levenshtein algorithm in Java

后端 未结 5 665
情深已故
情深已故 2021-02-08 20:16

I want to use the Levenshtein algorithm for the following task: if a user on my website searches for some value (he enters characters in a input), I want to instantly check for

5条回答
  •  忘了有多久
    2021-02-08 20:59

    You can use Apache Commons Lang3's StringUtils.getLevenshteinDistance():

    Find the Levenshtein distance between two Strings.

    This is the number of changes needed to change one String into another, where each change is a single character modification (deletion, insertion or substitution).

    The previous implementation of the Levenshtein distance algorithm was from http://www.merriampark.com/ld.htm

    Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError which can occur when my Java implementation is used with very large strings.

    This implementation of the Levenshtein distance algorithm is from http://www.merriampark.com/ldjava.htm

     StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException
     StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException
     StringUtils.getLevenshteinDistance("","")               = 0
     StringUtils.getLevenshteinDistance("","a")              = 1
     StringUtils.getLevenshteinDistance("aaapppp", "")       = 7
     StringUtils.getLevenshteinDistance("frog", "fog")       = 1
     StringUtils.getLevenshteinDistance("fly", "ant")        = 3
     StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
     StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
     StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
     StringUtils.getLevenshteinDistance("hello", "hallo")    = 1
    

提交回复
热议问题