763. Partition Labels 相同字母出现在同一块中,且块数最多

时间:2023-12-19 12:53:44

[抄题]:

A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

Example 1:

Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.

[暴力解法]:

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

又是index从0开始,长度不够因此需要加1

[思维问题]:

知道是前向指针,但是不知道怎么确定前面的i:存map[26],然后i顺着循环一遍就行了

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

763. Partition Labels 相同字母出现在同一块中,且块数最多

[一刷]:

不知道last怎么时候保持最大:math.max也是记忆化搜索的一种方式

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

确定前面的i:存map[26],然后i顺着循环一遍就行了

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

[是否头一次写此类driver funcion的代码] :

[潜台词] :

class Solution {
public List<Integer> partitionLabels(String S) {
//initialization: result, int[26]
List<Integer> result = new ArrayList<Integer>();
int[] map = new int[26]; //store the last position into the map
for (int i = 0; i < S.length(); i++) {
map[S.charAt(i) - 'a'] = i;
} //for loop: get the last, add last - start, reset start
int start = 0;
int last = 0;
for (int i = 0; i < S.length(); i++) {
//get the last
last = Math.max(last, map[S.charAt(i) - 'a']);
//add last - start, reset start
if (i == last) {
result.add(last - start + 1);
start = last + 1;
}
} //return
return result;
}
}