I am going through the CodingBat exercises for Java. Here is the one I have just completed:
Start with two arrays of strings,
a
andb
, each in alphabetical order, possibly with duplicates. Return the count of the number of strings which appear in both arrays. The best "linear" solution makes a single pass over both arrays, taking advantage of the fact that they are in alphabetical order.
Here is my code:
public int commonTwo(String[] a, String[] b){
String[] shortArray;
String[] longArray;
if (a.length != b.length) {
shortArray = a.length < b. length ? a : b;
longArray = a.length > b. length ? a : b;
} else {
shortArray = a;
longArray = b;
}
int count = 0;
String letterToAvoid = "";
for (int i = 0; i < shortArray.length; i++) {
for (int j = 0; j < longArray.length; j++) {
if (shortArray[i] == longArray[j] && longArray[j] != letterToAvoid){
count++;
letterToAvoid = longArray[j];
}
}
}
return count;
}
My questions are:
- Is there a better - or more efficient - way to find the longest and shortest
array
lengths (and subsequently assign them separately if the lengths are equal)? - Is my
letterToAvoid
idea, used to 'skip' certain array elements, good for this kind of exercise? - How could I make this code more efficient?