MueLu  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MueLu_ParameterListInterpreter.cpp
Go to the documentation of this file.
1 // @HEADER
2 // *****************************************************************************
3 // MueLu: A package for multigrid based preconditioning
4 //
5 // Copyright 2012 NTESS and the MueLu contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9 
10 #include <cstring>
11 #include <string>
12 #include <vector>
13 #include <algorithm>
14 
15 namespace MueLu {
16 
17 size_t LevenshteinDistance(const char* s, size_t len_s, const char* t, size_t len_t) {
18  // degenerate cases
19  if (len_s == 0) return len_t;
20  if (len_t == 0) return len_s;
21  if (!strncmp(s, t, std::min(len_s, len_t))) return 0;
22 
23  // create two work vectors of integer distances
24  size_t len = len_t + 1;
25  std::vector<size_t> v0(len);
26  std::vector<size_t> v1(len);
27 
28  // initialize v0 (the previous row of distances)
29  // this row is A[0][i]: edit distance for an empty s
30  // the distance is just the number of characters to delete from t
31  for (size_t i = 0; i < len; i++)
32  v0[i] = i;
33 
34  for (size_t i = 0; i < len_s; i++) {
35  // calculate v1 (current row distances) from the previous row v0
36 
37  // first element of v1 is A[i+1][0]
38  // edit distance is delete (i+1) chars from s to match empty t
39  v1[0] = i + 1;
40 
41  // use formula to fill in the rest of the row
42  for (size_t j = 0; j < len_t; j++) {
43  size_t cost = (s[i] == t[j]) ? 0 : 1;
44  v1[j + 1] = std::min(v1[j] + 1,
45  std::min(v0[j + 1] + 1,
46  v0[j] + cost));
47  }
48 
49  // copy v1 (current row) to v0 (previous row) for next iteration
50  for (size_t j = 0; j < len; j++)
51  v0[j] = v1[j];
52  }
53 
54  return v1[len_t];
55 }
56 
57 } // namespace MueLu
size_t LevenshteinDistance(const char *s, size_t len_s, const char *t, size_t len_t)