Ninja
edit_distance.cc
Go to the documentation of this file.
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "edit_distance.h"
16 
17 #include <algorithm>
18 #include <vector>
19 
20 int EditDistance(const StringPiece& s1,
21  const StringPiece& s2,
22  bool allow_replacements,
23  int max_edit_distance) {
24  // The algorithm implemented below is the "classic"
25  // dynamic-programming algorithm for computing the Levenshtein
26  // distance, which is described here:
27  //
28  // http://en.wikipedia.org/wiki/Levenshtein_distance
29  //
30  // Although the algorithm is typically described using an m x n
31  // array, only two rows are used at a time, so this implemenation
32  // just keeps two separate vectors for those two rows.
33  int m = s1.len_;
34  int n = s2.len_;
35 
36  vector<int> previous(n + 1);
37  vector<int> current(n + 1);
38 
39  for (int i = 0; i <= n; ++i)
40  previous[i] = i;
41 
42  for (int y = 1; y <= m; ++y) {
43  current[0] = y;
44  int best_this_row = current[0];
45 
46  for (int x = 1; x <= n; ++x) {
47  if (allow_replacements) {
48  current[x] = min(previous[x-1] + (s1.str_[y-1] == s2.str_[x-1] ? 0 : 1),
49  min(current[x-1], previous[x])+1);
50  }
51  else {
52  if (s1.str_[y-1] == s2.str_[x-1])
53  current[x] = previous[x-1];
54  else
55  current[x] = min(current[x-1], previous[x]) + 1;
56  }
57  best_this_row = min(best_this_row, current[x]);
58  }
59 
60  if (max_edit_distance && best_this_row > max_edit_distance)
61  return max_edit_distance + 1;
62 
63  current.swap(previous);
64  }
65 
66  return previous[n];
67 }
const char * str_
Definition: string_piece.h:49
StringPiece represents a slice of a string whose memory is managed externally.
Definition: string_piece.h:27
size_t len_
Definition: string_piece.h:50
int EditDistance(const StringPiece &s1, const StringPiece &s2, bool allow_replacements, int max_edit_distance)