String handling – Interview question

Find if two strings only differ by n characters. True if it does, false if it doesn’t

Krishna ,Krishnn, 1 =>true
Expanion, XEpanion, 2 => true
Expanion, APppanion, 1 => false


import java.util.Scanner;

public class StringMain {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str1 = scanner.nextLine();
        String str2 = scanner.nextLine();
        int diff = scanner.nextInt();
        if (str1 == null || str2 == null) {
            System.out.println("One of the string is null");
        }
        int actualDiff = compare(str1, str2);
        if (diff == actualDiff) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }

    private static int compare(String str1, String str2) {
        int diff = 0;
        char[] smallArray;
        char[] largeArray;
        if (str1.length() < str2.length()) {
            smallArray = str1.toCharArray();
            largeArray = str2.toCharArray();
        } else {
            smallArray = str2.toCharArray();
            largeArray = str1.toCharArray();
        }
        int i = 0;
        while (i < smallArray.length) {
            if (smallArray[i] != largeArray[i])
                diff++;
            i++;
        }
        diff += largeArray.length - i;
        return diff;
    }
}


Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s