Edit Distance

Overview

In this section we will try to solve a problem mentioned in Perl Weekly Challenge. The problem is called Edit Distance.

You are given two strings str1 and str2. Write a function to find out the minimum operations required to convert str1 into str2. The operations can be insert, remove or replace a character.

Example

Input: str1 = "kitten"; str2 = "sitting"
Output: 3

Operation 1: replace 'k' with 's'
Operation 2: replace 'e' with 'i'
Operation 3: insert 'g' at the end
Input: str1 = "sunday"; str2 = "monday"
Output: 2

Operation 1: replace 's' with 'm'
Operation 2: replace 'u' with 'o'

Code

Let’s look at the code now. We will iterate till the length of the smaller string. We will check if the characters are same – if they are not we will increment the counter. Then at the end of the iteration we will add the difference between the two string lengths.

private static int editDistance(String s1, String s2) {
    int len = s1.length();
    if (s2.length() < s1.length()) {
        len = s2.length();
    }
    int count = 0;
    for (int i = 0; i < len; i++) {
        if (s1.charAt(i) != s2.charAt(i)) {
            count++;
        }
    }
    return count + Math.abs(s1.length() - s2.length());
}

Let’s now see a Kotlin version of the same solution

private fun editDistance(s1: String, s2: String): Int {
    var len = s1.length
    if (s2.length < s1.length) {
        len = s2.length
    }
    var count = 0
    for (i in 0 until len) {
        if (s1[i] != s2[i]) {
            count++
        }
    }
    return count + Math.abs(s1.length - s2.length)
}

Conclusion

In this article we saw how to solve the edit distance problem in Java and Kotlin.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: