check一个字符串是否包含另一个字符串的所有字符,但不按顺序排列



我需要一个方法来获取字符串中的所有字符并检查这些字符是否在另一个字符串中

方法:

public boolean isItemUsable2(String word1, String word2) {
int count = 0;
for (int i = 0; i < word2.length(); i++) {
String itemPiece = Character.toString(word2.charAt(i));
if (word1.contains(itemPiece)) {
count++;
}
}
return count == word2.length();
}

问题是,例如单词1是"12345++"第二个单词是"155"它应该显示为假,因为只有一个5,但它显示为真,我不知道如何修复它。

可以通过使用字符列表作为搜索词来解决这个问题。尝试从列表中删除每个测试字符。如果它被成功删除,你就知道word1中包含了这个字符,同时阻止它再次被检查。

public static boolean isItemUsable2(String word1, String word2)
{
final List<Character> word1Chars = new ArrayList<>();
for (char aChar : word1.toCharArray())
word1Chars.add(aChar);
boolean usable = !word2.isEmpty();
for (int i = 0; i < word2.length() && usable; i++)
{
usable = word1Chars.remove((Character) word2.charAt(i));
}
return usable;
}

我会使用正则表达式。这不是最有效的方法,但它会起作用

public static boolean isItemUsable2(String a, String b) {
Map<Character, Integer> map = new HashMap<>();
for (char c : b.toCharArray()) {
map.merge(c, 1, (k,v) -> v + 1);
}
for (Entry<Character, Integer> entry : map.entrySet()) {
Pattern pattern = Pattern.compile(Pattern.quote(entry.getKey().toString()) + "{" + entry.getValue() + "}");
if (!pattern.matcher(a).find()) {
return false;
}
}
return true;
}

最新更新