I was asked to write down a Java function sharedStr
that by given 2 sorted arrays of String
s, returns the number of String
s that appear in both of the arrays.
The solution for this code must be linear, which means that I must go through each array only once. Otherwise, I could just compare each String
in the first array to all the String
s in the other array.
For example the following call to sharedStr
sharedStr({"Call","me","Ishmael"},{"Call","me","Jonha"});
must return 2
. I would like your help to understand what does it mean sorted arrays that contain String
s? There isn't any special description of the way the arrays have been sorted. What is the basic ordinary sorting of String
s?
How does one compare between two String
s anyway? If I try to do so, I get a compiler error. (I'm using Eclipse. I noticed that char
s can be compared automatically).
int x = 0;
int i= 0;
int j = 0;
while(i != list1.length && j != list2.length){
int v = list1[i].compareTo(list2[j]);
if (v == 0){
x++;i++;j++;
}else if (v < 0){
i++;
} else {
j++;
}
}
return x;
This makes the straightforward assumption that the strings are sorted using String.compareTo which would make sense.