I was asked to write down a Java function sharedStr that by given 2 sorted arrays of Strings, returns the number of Strings that appea
Because the arrays are sorted, you can step through them knowing you're walking them in order.
import java.util.List;
import java.util.LinkedList;
class StringTest {
static List sharedStrings(String[] a, String[] b) {
List result = new LinkedList();
int apos = 0;
int bpos = 0;
while(!(apos == a.length || bpos == b.length)) {
int comp = a[apos].compareTo(b[bpos]);
if(comp == 0) result.add(a[apos++]);
else if(comp > 0) bpos++;
else apos++;
}
return result;
}
public static void main(String[] args) {
String[] a = new String[]{"this","is","a","test"};
String[] b = new String[]{"test","for","a","party"};
java.util.Arrays.sort(a);
java.util.Arrays.sort(b);
List result = sharedStrings(a,b);
for(String s : result) System.out.println(s);
}
}