-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumLengthOfAConcatenatedStringWithUniqueCharacters.java
More file actions
86 lines (75 loc) · 2.79 KB
/
MaximumLengthOfAConcatenatedStringWithUniqueCharacters.java
File metadata and controls
86 lines (75 loc) · 2.79 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package leetcode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* MaximumLengthOfAConcatenatedStringWithUniqueCharacters
* https://leetcode-cn.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/
* 1239. 串联字符串的最大长度
* https://leetcode-cn.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/solution/bfsjie-ti-by-oshdyr-4pcc/
*
* @author tobin
* @since 2021-06-19
*/
public class MaximumLengthOfAConcatenatedStringWithUniqueCharacters {
public static void main(String[] args) {
MaximumLengthOfAConcatenatedStringWithUniqueCharacters sol = new MaximumLengthOfAConcatenatedStringWithUniqueCharacters();
System.out.println(sol.maxLength(Arrays.asList("un", "iq", "ue")));
System.out.println(sol.maxLength(Arrays.asList("cha", "r", "act", "ers")));
System.out.println(sol.maxLength(Arrays.asList("abcdefghijklmnopqrstuvwxyz")));
}
public int maxLength(List<String> arr) {
int maxCount = 0;
Map<Integer, Integer> graphCounts = new HashMap<>();
// parse each str
for (String str : arr) {
boolean flag = false;
// count chars
int[] charCounts = new int[26];
for (int i = 0; i < str.length(); i++) {
int cIdx = str.charAt(i) - 'a';
charCounts[cIdx]++;
if (charCounts[cIdx] > 1) {
flag = true;
break;
}
}
// skip str had duplicate chars
if (flag) {
continue;
}
int gCnt = str.length();
if (gCnt > maxCount) {
maxCount = gCnt;
}
// to graph idx;
int gIdx = toGraphIdx(charCounts);
Map<Integer, Integer> nextGraphCounts = new HashMap<>();
if (!graphCounts.containsKey(gIdx)) {
nextGraphCounts.put(gIdx, gCnt);
}
for (Map.Entry<Integer, Integer> entry : graphCounts.entrySet()) {
int key = entry.getKey();
int keyCount = entry.getValue();
if ((key & gIdx) == 0) {
int nextCount = keyCount + gCnt;
nextGraphCounts.put(key | gIdx, nextCount);
if (nextCount > maxCount) {
maxCount = nextCount;
}
}
}
graphCounts.putAll(nextGraphCounts);
// System.out.println();
}
return maxCount;
}
private int toGraphIdx(int[] charCounts) {
int res = 0;
for (int i = 0; i < 26; i++) {
res = (res << 1) + charCounts[i];
}
return res;
}
}