Determine if a string can be converted to another string if only insert / delete / replace operations are allowed

I have to write a function that takes two words (strings) as arguments and determines if the first word can be converted to the second word using only one first-order transformation.

  • First-order transformations change only one letter in a word

  • Allowed Conversions: Insert, Delete, and Replace

    • insert = insert a letter at any position in the word
    • remove = remove the letter from any position in the word
    • replace = replace the letter with another

Any suggestions? Any Java examples would be great!

+3
source share
4 answers

, s1 s2, .

  • , ,
    • , ,
  • ,
    • , ,

s1 s2, , equal.

Java:

static int firstDifference(String s1, String s2, int L) {
    for (int i = 0; i < L; i++) {
        if (s1.charAt(i) != s2.charAt(i)) {
            return i;
        }
    }
    return L;
}
static boolean oneEdit(String s1, String s2) {
    if (s1.length() > s2.length()) {
        return oneEdit(s2, s1);
    }
    final int L = s1.length();
    final int index = firstDifference(s1, s2, L);
    if (s1.length() == s2.length() && index != L) {
        return s1.substring(index+1).equals(s2.substring(index+1));
    } else if (s2.length() == L + 1) {
        return s1.substring(index).equals(s2.substring(index+1));
    } else {
        return false;
    }
}

:

    String[][] tests = {
        { "1", "" },
        { "123", "" },
        { "this", "that" },
        { "tit", "tat" },
        { "word", "sword" },
        { "desert", "dessert" },
        { "lulz", "lul" },
        { "same", "same" },
    };
    for (String[] test : tests) {
        System.out.printf("[%s|%s] = %s%n",
            test[0], test[1], oneEdit(test[0], test[1])
        );
    }

( ideone.com):

[1|] = true
[123|] = false
[this|that] = false
[tit|tat] = true
[word|sword] = true
[desert|dessert] = true
[lulz|lul] = true
[same|same] = false
+1

: , "before" "after" , , , .

, Brute Force Man Looping Lady.

+5

, , , , . , .

, . , , ? ? , , , ? , , , , , .

2 .

, , .

- . -, " ", . , ( , ), - .

+2

1 ( , char ). Google "Levenshtein java" .

" ", . char, , .: -)

+1
source

Source: https://habr.com/ru/post/1753352/


All Articles