summaryrefslogtreecommitdiffstats
path: root/llvm/lib/Support
diff options
context:
space:
mode:
authorDouglas Gregor <dgregor@apple.com>2009-12-30 17:23:44 +0000
committerDouglas Gregor <dgregor@apple.com>2009-12-30 17:23:44 +0000
commit165882c24067190779e78d5d5f9562a216334e9b (patch)
treec3ec7db4877ab9ea079f9d022357a75f58307c88 /llvm/lib/Support
parent2d435306e52445d173e289e98dc343afe94c7fa8 (diff)
downloadbcm5719-llvm-165882c24067190779e78d5d5f9562a216334e9b.tar.gz
bcm5719-llvm-165882c24067190779e78d5d5f9562a216334e9b.zip
Implement edit distance for StringRef
llvm-svn: 92309
Diffstat (limited to 'llvm/lib/Support')
-rw-r--r--llvm/lib/Support/StringRef.cpp31
1 files changed, 31 insertions, 0 deletions
diff --git a/llvm/lib/Support/StringRef.cpp b/llvm/lib/Support/StringRef.cpp
index 2d023e4895d..9084ea6ece0 100644
--- a/llvm/lib/Support/StringRef.cpp
+++ b/llvm/lib/Support/StringRef.cpp
@@ -8,6 +8,7 @@
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringRef.h"
+#include <vector>
using namespace llvm;
// MSVC emits references to this into the translation units which reference it.
@@ -35,6 +36,36 @@ int StringRef::compare_lower(StringRef RHS) const {
return Length < RHS.Length ? -1 : 1;
}
+/// \brief Compute the edit distance between the two given strings.
+unsigned StringRef::edit_distance(llvm::StringRef Other,
+ bool AllowReplacements) {
+ size_type m = size();
+ size_type n = Other.size();
+
+ std::vector<unsigned> previous(n+1, 0);
+ for (std::vector<unsigned>::size_type i = 0; i <= n; ++i)
+ previous[i] = i;
+
+ std::vector<unsigned> current(n+1, 0);
+ for (size_type y = 1; y <= m; ++y) {
+ current.assign(n+1, 0);
+ current[0] = y;
+ for (size_type x = 1; x <= n; ++x) {
+ if (AllowReplacements) {
+ current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u),
+ min(current[x-1], previous[x])+1);
+ }
+ else {
+ if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1];
+ else current[x] = min(current[x-1], previous[x]) + 1;
+ }
+ }
+ current.swap(previous);
+ }
+
+ return previous[n];
+}
+
//===----------------------------------------------------------------------===//
// String Searching
//===----------------------------------------------------------------------===//
OpenPOWER on IntegriCloud