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
First, the second part of your question:
Comparing strings in Java isn't as simple as:
if(sStringOne == sStringTwo)
//Equal
you should instead use methods of the string class
if(sStringOne.equals(sStringTwo)
// Equal
Second, the first part of your question:
Yes, it would be easy to loop through the first array and count each indexs occurence in the second array. Since you've specified each array must be iterated only once however, perhaps the following algorithm may suit:
If nothing was specified on what the ordering means, then it's probably indicative that it is the natural ordering of Strings which is lexicographic - from the JavaDoc for the appropriate function to compare two Strings - compareTo(), the definition of lexicographic ordering is copied and pasted below.
Note that using compareTo()
is different from simply checking the equality of two strings which is done using the equals() method (and not the ==
operator which doesn't doesn't check for 'meaningful' equality, only referential equality); compareTo
on the other hand will tell you what the relative ordering between two strings is i.e. are they equal (return value of 0) or does one come before the other?):
This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:
this.charAt(k)-anotherString.charAt(k)
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:
this.length()-anotherString.length()
This effectively means they're ordered alphabetically with shorter strings in lower case first, just like in a dictionary.