inLimbo
TUI Music Player that keeps you in Limbo.
 
Loading...
Searching...
No Matches
levenshtein.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <string>
5#include <vector>
6
15
36auto levenshteinDistance(const std::string& s1, const std::string& s2) -> size_t
37{
38 size_t len1 = s1.size();
39 size_t len2 = s2.size();
40
41 // 2D table to store the distances between substrings of s1 and s2.
42 std::vector<std::vector<size_t>> dist(len1 + 1, std::vector<size_t>(len2 + 1));
43
44 // Initialize the first column and row of the table.
45 for (size_t i = 0; i <= len1; ++i)
46 dist[i][0] = i;
47
48 for (size_t j = 0; j <= len2; ++j)
49 dist[0][j] = j;
50
51 // Fill the rest of the table with the calculated distances.
52 for (size_t i = 1; i <= len1; ++i)
53 {
54 for (size_t j = 1; j <= len2; ++j)
55 {
56 // If the characters at the current positions are the same, no cost to substitute.
57 size_t cost = (s1[i - 1] == s2[j - 1]) ? 0 : 1;
58
59 // Calculate the minimum of deletion, insertion, or substitution operations.
60 dist[i][j] = std::min({
61 dist[i - 1][j] + 1,
62 dist[i][j - 1] + 1,
63 dist[i - 1][j - 1] + cost
64 });
65 }
66 }
67
68 // Return the computed Levenshtein distance, which is the value at the bottom-right corner of the
69 // table.
70 return dist[len1][len2];
71}
auto levenshteinDistance(const std::string &s1, const std::string &s2) -> size_t
Computes the Levenshtein distance between two strings.
Definition levenshtein.hpp:36