標籤:貪心算法;難度:中等
思路:左起尋找第一個lastIndexOf,在該區間內找所包含的lastIndexOf,依情況延長
題目:
- 劃分字母區間
字符串 S 由小寫字母組成。我們要把這個字符串劃分爲儘可能多的片段,同一個字母只會出現在其中的一個片段。返回一個表示每個字符串片段的長度的列表。
示例 1:
輸入: S = “ababcbacadefegdehijhklij”
輸出: [9,7,8]
解釋:
劃分結果爲 “ababcbaca”, “defegde”, “hijhklij”。
每個字母最多出現在一個片段中。
像 “ababcbacadefegde”, “hijhklij” 的劃分是錯誤的,因爲劃分的片段數較少。
注意:
S的長度在[1, 500]之間。
S只包含小寫字母'a'到'z'。
解法:
/**
* @param {string} S
* @return {number[]}
*/
// 貪心算法 時間O(N) 空間O(N)
var partitionLabels = function(S) {
let res = []
for(let i = 0,len = S.length; i < len;){
if(S.lastIndexOf(S[i]) === i){
res.push(1)
i++
// }else if(S.lastIndexOf(S[i]) === S.length-1){
// res.push(S.length)
// i++
}else{
let maxIndex = S.lastIndexOf(S[i])
for(let j = i+1; j < maxIndex; j++) {
maxIndex = S.lastIndexOf(S[j]) > maxIndex ? S.lastIndexOf(S[j]) : maxIndex
}
res.push(maxIndex-i+1)
i = maxIndex + 1
}
}
return res
};