检查字符串是否由与另一个字符串相同的字母构建 [英] Check if a string is build out of the same letters as another string

查看:123
本文介绍了检查字符串是否由与另一个字符串相同的字母构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个主题很好地解释了我的想法。所以我想达到的是:

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?

推荐答案

您可以使用 String.toCharArray() Arrays.sort(char[]) Arrays.equals(char [],char []) 。也就是说,类似

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
}

输出是请求的

false
false
false
true

这篇关于检查字符串是否由与另一个字符串相同的字母构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆