[英]Check if a string is build out of the same letters as another string
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?
更简单的想法?
You could use String.toCharArray()
and Arrays.sort(char[])
and Arrays.equals(char[], char[])
. 您可以使用
String.toCharArray()
和Arrays.sort(char[])
和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
An easier idea: 更简单的想法:
s1
and s2
. s1
和s2
上的字母进行排序。 s1
and s2
. s1
和s2
删除重复的字母。 s1
is equal to s2
. s1
是否等于s2
。 If it is, then both strings are "made out of same letters". Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.