Check if a string is constructed of the same letters as another string
The topic explains my desire pretty well, I think. So what I want to achieve is:
madeOutOfSameLetters("aaasdf", "xyz") // false
madeOutOfSameLetters("aaasdf", "asdf") // false
madeOutOfSameLetters("aaasdf", "aaasdd") // false
madeOutOfSameLetters("aaasdf", "fdsaaa") // true
Is there a (combination of) method (s) that I can use, or do I need to do this myself?
In the second case, I will read each letter of both strings, write it to arrays and compare them with each other. But it seems harder than it does for me. Any simpler ideas?
+3
source to share
2 answers
You can use String.toCharArray()
both Arrays.sort(char[])
and Arrays.equals(char[], char[])
. That is, something like
public static boolean madeOutOfSameLetters(String a, String b) {
if (a == null) {
return b == null;
} else if (b == null) {
return false;
}
char[] left = a.toCharArray();
char[] right = b.toCharArray();
Arrays.sort(left);
Arrays.sort(right);
return Arrays.equals(left, right);
}
public static void main(String[] args) throws Exception {
System.out.println(madeOutOfSameLetters("aaasdf", "xyz")); // false
System.out.println(madeOutOfSameLetters("aaasdf", "asdf")); // false
System.out.println(madeOutOfSameLetters("aaasdf", "aaasdd")); // false
System.out.println(madeOutOfSameLetters("aaasdf", "fdsaaa"));// true
}
Conclusion - Requested
false
false
false
true
+12
source to share