aboutsummaryrefslogtreecommitdiff
path: root/challenge-224/lubos-kolouch/java/ch-1.java
blob: aeff01b10ff7304ea7ff56c556dbeb97d5b13174 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    System.out.println(canFormTarget("abc", "xyz")); // Output: false
    System.out.println(
        canFormTarget("scriptinglanguage", "perl"));    // Output: true
    System.out.println(canFormTarget("aabbcc", "abc")); // Output: true
  }

  public static boolean canFormTarget(String source, String target) {
    Map<Character, Integer> sourceChars = new HashMap<>();
    for (char c : source.toCharArray()) {
      sourceChars.put(c, sourceChars.getOrDefault(c, 0) + 1);
    }

    for (char c : target.toCharArray()) {
      if (!sourceChars.containsKey(c) || sourceChars.get(c) == 0) {
        return false;
      }
      sourceChars.put(c, sourceChars.get(c) - 1);
    }
    return true;
  }
}