简体   繁体   English

检查字符串是否与另一个字符串构成的字母相同

[英]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: 更简单的想法:

  1. Sort the letters on each string s1 and s2 . 对每个字符串s1s2上的字母进行排序。
  2. Remove duplicate letters from s1 and s2 . s1s2删除重复的字母。
  3. Check if s1 is equal to s2 . 检查s1是否等于s2 If it is, then both strings are "made out of same letters". 如果是,则两个字符串都是“由相同的字母组成”。 Otherwise, they don't. 否则,他们没有。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM