I have written a program that calculates the "cost" of transforming one string into another. I would like you to review it.
public class EditDistance {
public static void main(String[] args) {
// TODO Auto-generated method stub
String source="COTI",destination ="CAT";
System.out.println(getEditDistance(source,destination));
}
/**
* This function finds out the cost of transforming one string to
* another
* any change made to the string costs 1
* @param sourceString
* @param destinationString
* @return
*/
public static int getEditDistance(String sourceString, String destinationString) {
if (sourceString == null || destinationString == null){
throw new IllegalArgumentException("String cannot be null");
}
int distance = 0;
int sourceLength = sourceString.length() , destLength = destinationString.length();
for ( int i=0 ;i < sourceLength && i < destLength ; i++){
//how can I optimize loop condition, 3 conditions are checked on
//every iteration
if (sourceString.charAt(i) != destinationString.charAt(i)){
//if characters are unequal and increment the distance
distance++;
}
}
if (destLength != sourceLength ){
distance += Math.abs(sourceLength - destLength);
}
return distance;
}
}
However, I would like to optimize the loop condition. Currently, 3 operations are done.
What can I do to speed it up or make it more elegant?
"word"
and the string"sword"
have a distance of 1 instead of 5. I believe this is what Loufylouf is referring to as "Levenshtein distance". \$\endgroup\$ – JS1 Mar 10 '15 at 6:00