最多的不重叠子字符串Java
文章发布较早,内容可能过时,阅读注意甄别。
# 题目
给你一个只包含小写字母的字符串 s ,你需要找到 s 中最多数目的非空子字符串,满足如下条件:
- 这些字符串之间互不重叠,也就是说对于任意两个子字符串 s[i..j] 和 s[x..y] ,要么 j < x 要么 i > y 。
- 如果一个子字符串包含字符 char ,那么 s 中所有 char 字符都应该在这个子字符串中。 请你找到满足上述条件的最多子字符串数目。如果有多个解法有相同的子字符串数目,请返回这些子字符串总长度最小的一个解。可以证明最小总长度解是唯一的。
请注意,你可以以 任意 顺序返回最优解的子字符串。
示例 1:
输入:s = "adefaddaccc"
输出:["e","f","ccc"]
解释:下面为所有满足第二个条件的子字符串:
[
"adefaddaccc"
"adefadda",
"ef",
"e",
"f",
"ccc",
]
如果我们选择第一个字符串,那么我们无法再选择其他任何字符串,所以答案为 1 。如果我们选择 "adefadda" ,剩下子字符串中我们只可以选择 "ccc" ,它是唯一不重叠的子字符串,所以答案为 2 。同时我们可以发现,选择 "ef" 不是最优的,因为它可以被拆分成 2 个子字符串。所以最优解是选择 ["e","f","ccc"] ,答案为 3 。不存在别的相同数目子字符串解。
示例 2:
输入:s = "abbaccd"
输出:["d","bb","cc"]
解释:注意到解 ["d","abba","cc"] 答案也为 3 ,但它不是最优解,因为它的总长度更长。
提示:
- 1 <= s.length <= 10^5
- s 只包含小写英文字母。
# 思路
贪心
# 解法
class Solution {
public List<String> maxNumOfSubstrings(String s) {
List<int[]> res = getCandidateInterval(s);
Collections.sort(res, (o1, o2) -> (o1[1] - o1[0] - o2[1] + o2[0]));
for(int i = 0; i < res.size(); i++) {
for(int j = i - 1; j >= 0; j--) {
if(!(res.get(i)[0] > res.get(j)[1] || res.get(i)[1] < res.get(j)[0])) {
res.remove(i--);
break;
}
}
}
return res.stream().map(o -> (s.substring(o[0], o[1] + 1))).collect(Collectors.toList());
}
private List<int[]> getCandidateInterval(String s) {
char chs[] = s.toCharArray();
int end[] = new int[26];
for(int i = 0; i < s.length(); i++) {
end[chs[i] - 'a'] = i;
}
List<int[]> res = new ArrayList<>();
boolean vis[] = new boolean[26];
for(int i = 0; i < s.length(); i++) {
if(!vis[chs[i] - 'a']) {
int last = end[chs[i] - 'a'];
for(int j = i + 1; j <= last; j++) {
if(vis[chs[j] - 'a']) {
last = -1;
break;
}
last = Math.max(last, end[chs[j] - 'a']);
}
vis[chs[i] - 'a'] = true;
if(last != -1) {
res.add(new int[] {i, last});
}
}
}
return res;
}
}
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
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
# 总结
- 分析出几种情况,然后分别对各个情况实现


