一、題目描述
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.
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.
二、題解
方法一:枚舉區間
- 對於每一個字符,都會有一個終止位置,我們用
int end[]
數組每個字符記錄最後出現的位置。 - 枚舉區間
[0, end[s[l]-'a']
,在區間內可能會有字符的終止位置比當前字符還要遠,所以我們需要更新每一次查找的結束位置。
public List<Integer> partitionLabels(String S) {
char[] s = S.toCharArray();
int[] end = new int[26];
int N = s.length;
for (int i = 0; i < N; i++) {
end[s[i]-'a'] = i;
}
List<Integer> list = new LinkedList<>();
for (int l = 0; l < N;) {
int r = end[s[l]-'a'];
for (int k = l + 1; k < r; k++) {
if (end[s[k]-'a'] > r)
r = end[s[k]-'a'];
}
list.add(r - l + 1);
l = r + 1;
}
return list;
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,