Adap.tv Interview Question
Developer Program EngineersCountry: United States
If this is how the question was phrased, I would first clarify what is the goal of the comparison. Are we trying to find how similar/dis-similar, or just a simple true/false if they are exact or not? Also, is our comparison case-sensitive?
For this example I will use the following assumtions:
1. We want a true/false based on an exact match of the length/characters
2. Our comparison is indeed case sensitive (boo != Boo)
In my below example, I convert Java String to a character array so that the algorithm is applicable to other languages and not cluttered with Java's built-in String functions. Simply put, the algorithm for string comparison is:
1. Check for equal length, if not then return false.
2. Check sequentially through each array comparing 1 char at a time, if any are different then return false
3. If 1 and 2 both clear without returning false, then return true as they are the same.
public boolean compareStrings(String s1, String s2){
char[] first = s1.toArray();
char[] second = s2.toArray();
if(first.length != second.length){
return false;
}
for(int i = 0; i < first.length; i++){
if(first[i] != second[i]){
return false;
}
}
return true
}
- shravan40 September 13, 2013