[LeetCode] 763. Partition Labels
阿新 • • 發佈:2018-11-08
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.
題意:儘可能的把一個數組分解成多個,分解原則,相同的字母只能出現在一個數組裡
貪心的典型例子,關鍵在於每個字母最後出現的位置,每次都更新最大(位置靠後的那個),以那個為界拆就行了
class Solution { public List<Integer> partitionLabels(String S) {int[] lastIndex = new int[26]; for (int i = 0; i < S.length(); i++) { lastIndex[S.charAt(i) - 'a'] = i; } List<Integer> list = new ArrayList<>(); int i = 0; while (i < S.length()) { int j = lastIndex[S.charAt(i) - 'a'];for (int k = i; k < j; k++) { if (lastIndex[S.charAt(k) - 'a'] > j) j = lastIndex[S.charAt(k) - 'a']; } list.add(j - i + 1); if (j == S.length() - 1) break; i = j + 1; } return list; } }