原题链接在这里:https://leetcode.com/problems/partition-labels/description/
题目:
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.
Note:
S
will have length in range[1, 500]
.S
will consist of lowercase letters ('a'
to'z'
) only.
题解:
对于一个char, 找出她最先和最后出现的index. 然后像Merge Intervals结合交叉的部分.
可以先找出最后出现的index. 再iterate一遍, 每次遇到更大的最后出现index 便更新最远能跳的距离. 当到达最远能跳的距离时就说明到了融合后interval的末尾. 计算长度加到res中.
Time Complexity: O(S.length()). Space: O(1).
AC Java:
1 class Solution { 2 public ListpartitionLabels(String S) { 3 int [] last = new int[26]; 4 for(int i = 0; i ){ 5 last[S.charAt(i)-'a'] = i; 6 } 7 8 List res = new ArrayList (); 9 int maxJump = 0; 10 int start = 0; 11 for(int i = 0; i ){ 12 maxJump = Math.max(maxJump, last[S.charAt(i)-'a']); 13 if(i == maxJump){ 14 res.add(i-start+1); 15 start = i+1; 16 } 17 } 18 19 return res; 20 } 21 }