Libraryless. Click here for Pure Java version (63L/1K).
1 | static int leven(S s, S t) {
|
2 | // degenerate cases |
3 | if (s.equals(t)) return 0; |
4 | int ls = s.length(), lt = t.length(); |
5 | if (ls == 0) return lt; |
6 | if (lt == 0) return ls; |
7 | |
8 | // create two work vectors of integer distances |
9 | int[] v0 = new int[lt + 1]; |
10 | int[] v1 = new int[lt + 1]; |
11 | |
12 | // initialize v0 (the previous row of distances) |
13 | // this row is A[0][i]: edit distance for an empty s |
14 | // the distance is just the number of characters to delete from t |
15 | for (int i = 0; i < v0.length; i++) |
16 | v0[i] = i; |
17 | |
18 | for (int i = 0; i < ls; i++) |
19 | {
|
20 | // calculate v1 (current row distances) from the previous row v0 |
21 | |
22 | // first element of v1 is A[i+1][0] |
23 | // edit distance is delete (i+1) chars from s to match empty t |
24 | v1[0] = i + 1; |
25 | |
26 | // use formula to fill in the rest of the row |
27 | for (int j = 0; j < lt; j++) |
28 | {
|
29 | int cost = s.charAt(i) == t.charAt(j) ? 0 : 1; |
30 | v1[j + 1] = Math.min(Math.min(v1[j] + 1, v0[j + 1] + 1), v0[j] + cost); |
31 | } |
32 | |
33 | // swap arrays |
34 | int[] v = v1; v1 = v0; v0 = v; |
35 | } |
36 | |
37 | return v0[lt]; |
38 | } |
from Wikipedia, translated to JavaX
download show line numbers debug dex old transpilations
Travelled to 17 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, ekrmjmnbrukm, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt, whxojlpjdney
No comments. add comment
| Snippet ID: | #1000388 |
| Snippet name: | leven - Levenshtein string distance function in JavaX |
| Eternal ID of this version: | #1000388/4 |
| Text MD5: | d5a257ec5dec20df71bacac86510ca3e |
| Transpilation MD5: | d43f5c3c26a20be2332b7f990eb40401 |
| Author: | stefan |
| Category: | javax |
| Type: | JavaX fragment (include) |
| Public (visible to everyone): | Yes |
| Archived (hidden from active list): | No |
| Created/modified: | 2019-11-20 00:19:02 |
| Source code size: | 1117 bytes / 38 lines |
| Pitched / IR pitched: | No / No |
| Views / Downloads: | 990 / 3266 |
| Version history: | 3 change(s) |
| Referenced in: | [show references] |