首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用swift优化循环的双行程

使用swift优化循环的双行程
EN

Stack Overflow用户
提问于 2020-01-20 21:23:43
回答 1查看 142关注 0票数 1

我使用最小编辑距离算法来查找数组中最相似的字符串的束。

因此,我必须遍历双for循环来比较所有元素。

如果数据量足够大,则该算法的效率很低。

有没有优化的方法?

代码语言:javascript
复制
let data = [
  "10000", // count
  "asdfqwerty", "asdfzxcvgh", "asdfpoiuyt",
  ...
]

for i in 1..<data.count {
  let string = data[i]
  for j in (i + 1)..<data.count {
    let newMin = string.minimumEditDistance(other: data[j])

    if min >= newMin {
      // some logic
    }
  }
}
代码语言:javascript
复制
extension String {
  public func minimumEditDistance(other: String, `default`: Int = 10) -> Int {
    let m = self.count
    let n = other.count

    if m == 0 || n == 0 {
      return `default`
    }

    var matrix = [[Int]](repeating: [Int](repeating: 0, count: n + 1), count: m + 1)

    // initialize matrix
    for index in 1...m {
      // the distance of any first string to an empty second string
      matrix[index][0] = index
    }

    for index in 1...n {
      // the distance of any second string to an empty first string
      matrix[0][index] = index
    }

    // compute Levenshtein distance
    for (i, selfChar) in self.enumerated() {
      for (j, otherChar) in other.enumerated() {
        if otherChar == selfChar {
          // substitution of equal symbols with cost 0
          matrix[i + 1][j + 1] = matrix[i][j]
        } else {
          // minimum of the cost of insertion, deletion, or substitution
          // added to the already computed costs in the corresponding cells
          matrix[i + 1][j + 1] = Swift.min(matrix[i][j] + 1, matrix[i + 1][j] + 1, matrix[i][j + 1] + 1)
        }
      }
    }
    return matrix[m][n]
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-20 21:58:09

您可以通过使用minimumEditDistance作为排序函数对数组进行排序,然后获取第一个或最后一个元素(取决于您如何定义排序)以及您需要的元素-最小值或最大值,从而实现所需的行为。它可能会在O(N*log(N))时间内运行。这已经比指数更好了。

正如@Sultan提到的,它并不适用于所有距离,因为传递性仅适用于度量(定义集合中每个元素之间的距离的函数)。您正在使用Levenstain距离作为编辑距离算法,这确实是一个度量。我提到的解决方案在某些情况下应该有助于优化。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59824246

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档