Check if a string is build out of the same letters as another string

落爺英雄遲暮 提交于 2019-12-12 14:24:05

问题


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:

  1. Sort the letters on each string s1 and s2.
  2. Remove duplicate letters from s1 and s2.
  3. Check if s1 is equal to s2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!