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
27
28
29
30
31
32
33
34
35
|
import java.util.*;
class Solution {
public boolean isSolvable(String[] words, String result) {
Set<Character> charsSet = new HashSet<>();
for (String w : words) for (char c : w.toCharArray()) charsSet.add(c);
for (char c : result.toCharArray()) charsSet.add(c);
if (charsSet.size() > 10) return false;
List<Character> chars = new ArrayList<>(charsSet);
Set<Character> firstLetters = new HashSet<>();
for (String w : words) firstLetters.add(w.charAt(0));
firstLetters.add(result.charAt(0));
Map<Character, Integer> coeff = new HashMap<>();
for (String w : words) for (int i = 0; i < w.length(); i++) coeff.put(w.charAt(w.length()-1-i), coeff.getOrDefault(w.charAt(w.length()-1-i), 0) + (int)Math.pow(10, i));
for (int i = 0; i < result.length(); i++) coeff.put(result.charAt(result.length()-1-i), coeff.getOrDefault(result.charAt(result.length()-1-i), 0) - (int)Math.pow(10, i));
boolean[] used = new boolean[10];
Map<Character, Integer> charToDigit = new HashMap<>();
return backtrack(0, chars, used, charToDigit, coeff, firstLetters);
}
private boolean backtrack(int idx, List<Character> chars, boolean[] used, Map<Character, Integer> charToDigit, Map<Character, Integer> coeff, Set<Character> firstLetters) {
if (idx == chars.size()) {
long total = 0;
for (char c : coeff.keySet()) total += coeff.get(c) * charToDigit.get(c);
return total == 0;
}
char c = chars.get(idx);
for (int d = 0; d < 10; d++) {
if (used[d]) continue;
if (d == 0 && firstLetters.contains(c)) continue;
charToDigit.put(c, d); used[d] = true;
if (backtrack(idx+1, chars, used, charToDigit, coeff, firstLetters)) return true;
used[d] = false; charToDigit.remove(c);
}
return false;
}
}
|