0

I need a Method that takes all the characters of a String and checks if those characters are in another String.

The Method I have:

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();
    }

The problem is, for example word 1 is "12345++" and word 2 is "155" it should say it's false since there is only one 5, but it shows true and I don't know how to fix it.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    you'd need to "remember" that you already looked for a `5`, and where you found it. Then, when you look for the 2nd `5`, it should be after the first `5`. I recommend looking at [`Map`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Map.html), [`String.indexOf(char)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#indexOf(int)) and [`String.indexOf(char, int)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#indexOf(int,int)). – Turing85 Jan 18 '23 at 19:28
  • 1
    Alternatively, you can check [this question](https://stackoverflow.com/q/6712587/10819573). Once you create the frequency maps of the two strings, you can easily check what you want. – Arvind Kumar Avinash Jan 18 '23 at 19:40

2 Answers2

0

You can solve this problem by using a List of characters for the search word. Attempt to remove each test character from the list. If it is successfully removed, you know word1 contained the character while simultaneously preventing it from being checked again.

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;
}
Jake Henry
  • 303
  • 1
  • 10
0

I would use regex. This isn't the most efficient way to do it, but it will work

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;
}
Ryan
  • 1,762
  • 6
  • 11