Java题解 | #分品种#
分品种
https://www.nowcoder.com/practice/9af4e93b04484df79d4cc7a863343b0b
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型一维数组
*/
public int[] partitionLabels (String s) {
// write code here
int[] lastOccur = new int[26];
for (int i = 0; i < 26; i++) {
lastOccur[i] = -1;
}
int n = s.length();
for (int i = 0; i < n; i++) {
lastOccur[s.charAt(i) - 'a'] = i;
}
List<Integer> partitions = new ArrayList<>();
int start = 0;
int end = 0;
for (int i = 0; i < n; i++) {
end = Math.max(end, lastOccur[s.charAt(i) - 'a']);
if (i == end) {
partitions.add(end - start + 1);
start = end + 1;
}
}
int[] result = new int[partitions.size()];
for (int i = 0; i < partitions.size(); i++) {
result[i] = partitions.get(i);
}
return result;
}
}
使用的是Java编程语言。
该题考察的知识点主要是字符串的处理和数组的操作
代码的文字解释如下:
- 创建数组
lastOccur用于记录每个小写字母最后一次出现的索引。初始值设为-1。 - 遍历字符串
s的每个字符,更新lastOccur数组中对应字符的值为当前索引。 - 创建一个列表
partitions,用于存储每个子串的长度。 - 设置两个指针
start和end,初始值都为0,分别表示当前子串的起始位置和结束位置。 - 遍历字符串
s的每个字符,更新end的值为当前字符最后一次出现的索引。 - 如果当前索引等于
end,说明当前子串已经结束,将子串长度添加到partitions列表中,并更新start的值为end + 1。 - 将
partitions列表转换成整数数组result,并返回结果。

