Edit Distance Levenshtein DP (Rust)
Compute the Levenshtein edit distance between two Rust strings with insert, delete, and substitute operations.
Code
fn edit_distance(a: &str, b: &str) -> usize {
let a: Vec<char> = a.chars().collect(); let b: Vec<char> = b.chars().collect();
let (m, n) = (a.len(), b.len());
let mut prev: Vec<usize> = (0..=n).collect();
for i in 1..=m {
let mut curr = vec![0usize; n + 1]; curr[0] = i;
for j in 1..=n { if a[i - 1] == b[j - 1] { curr[j] = prev[j - 1]; } else { curr[j] = 1 + prev[j].min(curr[j - 1]).min(prev[j - 1]); } }
prev = curr;
}
prev[n]
}How it works
Edit Distance Levenshtein DP (Rust) keeps everything in the function edit_distance.
Repetition is confined to for i in 1..=m — the rest of the file is straight-line.
Applying it
Entry signature: fn edit_distance(a: &str, b: &str) -> usize
The surface worth importing is edit_distance; the helpers around it are private to the snippet.
Statements that matter
let a: Vec<char> = a.chars().collect(); let b: Vec<char> = b.chars().collect();
let mut prev: Vec<usize> = (0..=n).collect();
Interactive Tools for This Topic
Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `edit_distance` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.