题解 | #分品种#
分品种
https://www.nowcoder.com/practice/9af4e93b04484df79d4cc7a863343b0b
题目考察的知识点:贪心
题目解答方法的文字分析:
创建一个长度为 26 的数组 result,用于记录每个字母在字符串 s 中最后出现的位置。
先考虑s[i]位置出现的最后位置end,然后end是可以向右延伸的,取决于i~end之间的字母的新的出现的靠右的位置(即更新end=max(end,result[s.charAt(i) - 'a']),其中l<=i<=end) 当更新到上界end仍不能再更新时,说明此时的片段内出现的字母以后不会再出现了,可以更新答案了。
本题解析所用的编程语言:Java
完整且正确的编程代码
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型一维数组
*/
public int[] partitionLabels (String s) {
// write code here
int [] result = new int[26];
for (int i = 0; i < s.length(); i++) {
result[s.charAt(i) - 'a'] = i;
}
ArrayList<Integer> arrayList = new ArrayList<>();
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
end = Math.max(end, result[s.charAt(i) - 'a']);
if (i == end) {
arrayList.add(end - start + 1);
start = end + 1;
}
}
int [] arr = new int[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
arr[i] = arrayList.get(i);
}
return arr;
}
}