github.com/zhongdalu/gf@v1.0.0/g/text/gstr/gstr_levenshtein.go (about) 1 // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 package gstr 8 9 // Levenshtein calculates Levenshtein distance between two strings. 10 // costIns: Defines the cost of insertion. 11 // costRep: Defines the cost of replacement. 12 // costDel: Defines the cost of deletion. 13 // See http://php.net/manual/en/function.levenshtein.php. 14 func Levenshtein(str1, str2 string, costIns, costRep, costDel int) int { 15 var maxLen = 255 16 l1 := len(str1) 17 l2 := len(str2) 18 if l1 == 0 { 19 return l2 * costIns 20 } 21 if l2 == 0 { 22 return l1 * costDel 23 } 24 if l1 > maxLen || l2 > maxLen { 25 return -1 26 } 27 28 tmp := make([]int, l2+1) 29 p1 := make([]int, l2+1) 30 p2 := make([]int, l2+1) 31 var c0, c1, c2 int 32 var i1, i2 int 33 for i2 := 0; i2 <= l2; i2++ { 34 p1[i2] = i2 * costIns 35 } 36 for i1 = 0; i1 < l1; i1++ { 37 p2[0] = p1[0] + costDel 38 for i2 = 0; i2 < l2; i2++ { 39 if str1[i1] == str2[i2] { 40 c0 = p1[i2] 41 } else { 42 c0 = p1[i2] + costRep 43 } 44 c1 = p1[i2+1] + costDel 45 if c1 < c0 { 46 c0 = c1 47 } 48 c2 = p2[i2] + costIns 49 if c2 < c0 { 50 c0 = c2 51 } 52 p2[i2+1] = c0 53 } 54 tmp = p1 55 p1 = p2 56 p2 = tmp 57 } 58 c0 = p1[l2] 59 60 return c0 61 }