问题
The topic explains my wish pretty well i think. So what i want to reach is:
madeOutOfSameLetters("aaasdf", "xyz") // false
madeOutOfSameLetters("aaasdf", "asdf") // false
madeOutOfSameLetters("aaasdf", "aaasdd") // false
madeOutOfSameLetters("aaasdf", "fdsaaa") // true
Is there a (combination of) method(s) I can use for, or do I need to do it by my own?
In second case I would count each letter of both strings, write it into arrays and compare them to each other. But that seems to be more complicated than it has to be to me. Any easier ideas?
回答1:
You could use String.toCharArray() and 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
}
Output is the requested
false
false
false
true
回答2:
An easier idea:
- Sort the letters on each string
s1
ands2
. - Remove duplicate letters from
s1
ands2
. - Check if
s1
is equal tos2
. If it is, then both strings are "made out of same letters". Otherwise, they don't.
Hope it helps.
来源:https://stackoverflow.com/questions/25912963/check-if-a-string-is-build-out-of-the-same-letters-as-another-string