JavaBeginner
JavaBeginner

Reputation: 105

Basic java code to compare char of two strings

I want to write code that accepts two strings and returns the sum of the number of times when the char of both string does not match.

public int solution(String s1, String s2) {
    int sum = 0;
    for (int i=0; i<s1.length(); i++){
        if (s1.charAt(i) != s2.charAt(i))
            sum++;
    }
    return sum;
}

This code of run when the length of the two strings are the same. I want to what I need to add to the code so that if the length of string 1 > length of string 2, the code still run and also include the # char chat wasn't able to be compare to string 2 because string 2 is shorter. (vice versa)

ex:

s1: aaaaab
s2: ac

==> sum =5

or

s1: ab
s2: abbbb

==> sum = 3

Upvotes: 0

Views: 276

Answers (2)

owenrb
owenrb

Reputation: 535

Find the min and max length of both string.

int min = 0, max = 0;
if(s1.length() > s2.length()) {
   max = s1.length();
   min = s2.length();
} else {
   min = s1.length();
   max = s2.length();
}

traverse only up to the minimum length

for (int i=0; i<min; i++){
   if (s1.charAt(i) != s2.charAt(i)) {
      sum++;
   }
}

then add the difference of max and min in the return value

 return sum + (max - min);

Upvotes: 2

BitTickler
BitTickler

Reputation: 11947

The number you seek is a composite of 2 steps:

  1. The number of differences between the strings from 0 to Math.min(s1.length(),s2.length()) as you do it in your code.
  2. The difference in length of both strings. Math.abs(s1.length()-s2.length()).

Add the numbers from (1) and (2) and it shall be the number thou seeketh ;)

Upvotes: 2

Related Questions