|
| 1 | +// 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. |
| 2 | +// |
| 3 | +// Example 1: |
| 4 | +// Input: S = "ababcbacadefegdehijhklij" |
| 5 | +// Output: [9,7,8] |
| 6 | +// Explanation: |
| 7 | +// The partition is "ababcbaca", "defegde", "hijhklij". |
| 8 | +// This is a partition so that each letter appears in at most one part. |
| 9 | +// A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts. |
| 10 | +// |
| 11 | +// Note: |
| 12 | +// |
| 13 | +// S will have length in range [1, 500]. |
| 14 | +// S will consist of lowercase letters ('a' to 'z') only. |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {string} S |
| 18 | + * @return {number[]} |
| 19 | + */ |
| 20 | + |
| 21 | +/** Greedy */ |
| 22 | +// Let's try to repeatedly choose the smallest left-justified partition. |
| 23 | +// Consider the first label, say it's 'a'. The first partition must include it, and also the last occurrence of 'a'. |
| 24 | +// However, between those two occurrences of 'a', there could be other labels that make the minimum size of this partition bigger. |
| 25 | +// For example, in "abccaddbeffe", the minimum first partition is "abccaddb". |
| 26 | +// This gives us the idea for the algorithm: For each letter encountered, process the last occurrence of that letter, |
| 27 | +// extending the current partition [start, end] appropriately. |
| 28 | +function partitionLabels(S) { |
| 29 | + if (S == null || S.length === 0) return null; |
| 30 | + |
| 31 | + const res = []; |
| 32 | + const map = {}; // record the last seen index of the each char |
| 33 | + |
| 34 | + for (let i = 0; i < S.length; i++) { |
| 35 | + map[S[i]] = i; |
| 36 | + } |
| 37 | + |
| 38 | + // record the end index of the current sub string |
| 39 | + let last = 0; |
| 40 | + let start = 0; |
| 41 | + for (let i = 0; i < S.length; i++) { |
| 42 | + last = Math.max(last, map[S[i]]); |
| 43 | + if (last === i) { |
| 44 | + res.push(last - start + 1); |
| 45 | + start = last + 1; |
| 46 | + } |
| 47 | + } |
| 48 | + return res; |
| 49 | +} |
0 commit comments