how to efficiently check if the Levenshtein edit distance between two string is 1 [closed]

本小妞迷上赌 提交于 2019-12-13 00:40:43

问题


please note that it doesn't require to really calculate Levenshtein edit distance. just check it's 1 or not.

The signature of the method may look like this:

bool Is1EditDistance(string s1, string s2). 

for example: 1. "abc" and "ab" return true 2. "abc" and "aebc" return true 3. "abc" and "a" return false.

I've tried recursive approve, but it it not efficient.


update: got answer from a friend:

        for (int i = 0; i < s1.Length && i < s2.Length; i++)
        {
            if (s1[i] != s2[i])
            {
                return s1.Substring(i + 1) == s2.Substring(i + 1)   //case of change
                    || s1.Substring(i + 1) == s2.Substring(i)       //case of s1 has extra
                    || s1.Substring(i) == s2.Substring(i + 1);      //case of s2 has extra
            }
        }
        return Math.Abs(s1.Length - s2.Length) == 1;

回答1:


If you only care if the distance is exactly 1 or not, you can do something like this:

  • If the difference of the strings' lengths is not 0 or 1, return false.
  • If both strings have length n, loop i = 0..n checking s1[i] == s2[i] for all i except one.
  • If the strings have length n and n+1, let i be the smallest index where s1[i] != s2[i], then loop j=i..n checking s1[j] == s2[j+1] for all j.


来源:https://stackoverflow.com/questions/12632825/how-to-efficiently-check-if-the-levenshtein-edit-distance-between-two-string-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!