How to check equality of two String objects independent of the char order?
Examples:
checkEq(A*B'*C,B'*A*C) has to return true
checkEq(A*B'*C,A*B*C) ----> false... etc
Try using the java str.split method. For instance, str.split("*") will give you an array of the elements A,B,C or B,A,C. And then just sort them and single loop through them once to compare them.
String str1 = "A*B*C";
String str2 = "C*A*B";
// split strings into arrays
String[] array1 = str1.split("*");
String[] array2 = str2.split("*");
// sort each array
Arrays.sort(array1);
Arrays.sort(array2);
// compare arrays
for( i=0; i<array1.length; i++ ){
if(array1[i] == array2[i]){
return false; // OR, do whatever it is you want to do here.
}
}
You could put the individual characters into a Set<Character> or a Map<Character, Integer> (use the latter if you care about multiples of the same character). Then calculating the set differences both ways will tell you if there are characters in one string that don't appear in the other (thus they are not equal). For the map, calculate set difference (like above) on the key set, then if equal, the difference of each corresponding value -- if all are 0, the two strings are equal in the question's sense of equality.
checkEq(A*B'*C, A'*B*C)should return true or false? can you explain what's your algorithm or what's the specific problem you have trying to solve this problem?