763. Partition Labels
Problem:
Greedy.
Use a map the store the last index of each char's appearance. what makes the partition successful is that the last appearance (end) stops to increment. It means no char from start to end appears after end.
Solution:
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.
Greedy.
Use a map the store the last index of each char's appearance. what makes the partition successful is that the last appearance (end) stops to increment. It means no char from start to end appears after end.
Solution:
class Solution { public List<Integer> partitionLabels(String S) { List<Integer> res = new ArrayList<>(); if (S == null || S.length() == 0) return res; Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < S.length(); i++) { map.put(S.charAt(i), i); } int start = 0, end = 0; for (int i = 0; i < S.length(); i++) { end = Math.max(end, map.get(S.charAt(i))); if (end == i) { res.add(end - start + 1); start = end + 1; } } return res; } }
评论
发表评论