https://leetcode.com/problems/partition-labels/
将问题转化成线段分割问题:找到所有可以切的点,使得每一个线段都不会被切到
class Solution {
public List<Integer> partitionLabels(String s) {
int[][] range = new int[26][2];
for (int i = 0; i < 26; i++) {
range[i][0] = -1;
range[i][1] = -1;
}
for (int i = 0; i < s.length(); i++) {
int p = s.charAt(i) - 'a';
if (range[p][0] == -1) range[p][0] = i;
range[p][1] = i;
}
Arrays.sort(range, (o1, o2) -> {
if (o1[0] == o2[0]) return o1[1] - o2[1];
else return o1[0] - o2[0];
});
List<Integer> result = new ArrayList<>();
int start = -1;
int end = -1;
for (int[] r : range) {
if (r[0] == -1) {
continue;
} else if (start == -1) {
start = r[0];
end = r[1];
} else {
if (r[0] > start && r[0] < end) {
end = Math.max(end, r[1]);
} else {
result.add(end - start + 1);
start = r[0];
end = r[1];
}
}
}
result.add(end - start + 1);
return result;
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/sinat_42483341/article/details/121648167
内容来源于网络,如有侵权,请联系作者删除!