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


Simple idea:

  • Sort letters in each line s1

    and s2

    .
  • Remove duplicate letters from s1

    and s2

    .
  • Check if it matches s1

    s2

    . If so, then both strings are "made of the same letters." Otherwise, they don't.


Hope it helps.

+4


source







All Articles