763. Partition Labels - Medium
前往題目
想法
- 不知道如何判斷
partition
在何時結束
思路
其實很簡單,疊代s
的字符,每次都取最大的終點,這樣在一個partition
結束時指針就會剛好等於end
,因為此區間沒有更遠的字符了
- 紀錄每個字符(總共26個小寫字母)的終點
- 疊代
s
的所有字符,每次更新size
和終點 - 指針等於終點的時候就是一個
partition
結束的時候 - 加入結果,並且歸零
size
Code
class Solution {
public List<Integer> partitionLabels(String s) {
List<Integer> res = new ArrayList<>();
int[] map = new int[26]; // alphabet -> lastIndex
// Store each character's last position
for (int i = 0; i < s.length(); ++i) {
map[s.charAt(i) - 'a'] = i;
}
// Keep track of the partition size
int size = 0;
// The temp end of the partition
int end = 0;
// Go through the string
for (int i = 0; i < s.length(); ++i) {
++size;
end = Math.max(end, map[s.charAt(i) - 'a']);
// Reach the end of the current partition
if (i == end) {
res.add(size);
size = 0;
}
}
return res;
}
}
763. Partition Labels - Medium
https://f88083.github.io/2024/03/11/763-Partition-Labels-Medium/