Measure the distance between two strings with Ruby?

后端 未结 6 1969
-上瘾入骨i
-上瘾入骨i 2020-11-29 08:18

Can I measure the distance between two strings with Ruby?

I.e.:

compare(\'Test\', \'est\') # Returns 1
compare(\'Test\', \'Tes\') #          


        
6条回答
  •  醉梦人生
    2020-11-29 08:37

    I like DigitalRoss' solution above. However, as pointed out by dawg, its runtime grows on the order O(3^n), which is no good for longer strings. That solution can be sped up significantly using memoization, or 'dynamic programming':

    def lev(string1, string2, memo={})
      return memo[[string1, string2]] if memo[[string1, string2]]
      return string2.size if string1.empty?
      return string1.size if string2.empty?
      min = [ lev(string1.chop, string2, memo) + 1,
              lev(string1, string2.chop, memo) + 1,
              lev(string1.chop, string2.chop, memo) + (string1[-1] == string2[-1] ? 0 : 1)
           ].min
      memo[[string1, string2]] = min
      min
    end
    

    We then have much better runtime, (I think it's almost linear? I'm not really sure).

    [9] pry(main)> require 'benchmark'
    => true
    [10] pry(main)> @memo = {}
    => {}
    [11] pry(main)> Benchmark.realtime{puts lev("Hello darkness my old friend", "I've come to talk with you again")}
    26
    => 0.007071999832987785
    

提交回复
热议问题