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 appea
Go with the assumption that the two lists are sorted before entering your sharedStr
algorithm. You'd want to keep two references: each to an element in each of the two lists.
Then you'd start comparing element after element and progress either or both of the references accordingly. Here's a pseudo-code:
def sharedStr(lista, listb):
indexa = indexb = 0
shared = 0
while 1:
try:
a = lista[indexa]
b = listb[indexb]
except IndexError: # we fell off one of the lists
break
if a == b:
shared += 1
indexa += 1
indexb += 1
elif a < b:
indexa += 1
else: # b < a
indexb += 1
return shared
Yes, this is also a valid Python code. ;-)
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.
.equals()
(for boolean) or .compareTo()
(for relational comparison) For instance:.
String a = "Hello";
a.equals("Hello"); // true
String b = "Not hi";
b.equals(a); // false
Be careful accidentally using ==
- for constant strings, due to VM designs, it may actually say two Strings are equal, as they are in fact the same object.
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<String> sharedStrings(String[] a, String[] b) {
List<String> result = new LinkedList<String>();
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<String> result = sharedStrings(a,b);
for(String s : result) System.out.println(s);
}
}
The fact that the arrays are sorted is a red herring, it is irrelevant to the solution. Use a Map<String, Integer> Steps:
What does it mean sorted arrays that contains strings? There isn't any special description of the way it has been sorted. what is the basic ordinary sorting of strings?
It means the elements in the array are ordered in a natural sequence. For strings this is alphebetical order with lowercase words place before upper case.
How does one compare between two strings any way?
By invoking the compareTo
method. If it returns 0 they strings are equal, if return < 0 the first string is lower than the second, if return > 0 the firs string is higher than the second.
As for how to count repetitions linearly see this: comparing strings in java