763. 划分字母区间
作者:互联网
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-labels
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
计数
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
class Solution {
private boolean ok(int[] a, int[] b) {
for (int i = 0; i < a.length; ++i) {
if (b[i] != 0 && b[i] != a[i]) {
return false;
}
}
return true;
}
public List<Integer> partitionLabels(String s) {
if (s == null || s.length() == 0) {
return Collections.emptyList();
}
int[] cnt = new int[26];
for (int i = 0; i < s.length(); ++i) {
cnt[s.charAt(i) - 'a']++;
}
List<Integer> ans = new ArrayList<>();
int left = 0, right = 0;
int[] window = new int[26];
while (right < s.length()) {
window[s.charAt(right) - 'a']++;
if (ok(cnt, window)) {
ans.add(right - left + 1);
window = new int[26];
left = right + 1;
}
right++;
}
return ans;
}
}
记录最后出现下标
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> partitionLabels(String s) {
int[] last = new int[26];
int length = s.length();
for (int i = 0; i < length; i++) {
last[s.charAt(i) - 'a'] = i;
}
List<Integer> partition = new ArrayList<>();
int start = 0, end = 0;
for (int i = 0; i < length; i++) {
end = Math.max(end, last[s.charAt(i) - 'a']);
if (i == end) {
partition.add(end - start + 1);
start = end + 1;
}
}
return partition;
}
}
标签:right,java,int,763,字母,划分,++,length,end 来源: https://www.cnblogs.com/tianyiya/p/15818046.html