0

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
4
  • 5
    Your code snippet is not valid Java, which makes it hard to understand exactly what you're looking for. Commented Mar 25, 2012 at 18:38
  • 1
    This is not string equality. You are just checking that string a and string b are composed of the exact same characters, in any order. Commented Mar 25, 2012 at 18:40
  • 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? Commented Mar 25, 2012 at 19:05
  • Insufficiently specified. Do the strings have to be the same length? What about repeated characters? Commented Mar 25, 2012 at 21:39

3 Answers 3

5

Sort the string by character and compare:

    char[] a1 = s1.toCharArray();
    Arrays.sort(a1);
    char[] a2 = s2.toCharArray();
    Arrays.sort(a2);
    return Arrays.equals(a1,a2);
Sign up to request clarification or add additional context in comments.

Comments

1

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.
   }
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.