763. Partition Labels

Question

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:

  1. S will have length in range [1, 500].
  2. S will consist of lowercase letters (ā€˜aā€™ to ā€˜zā€™) only.

Solution

  • Method 1: Greedy
    class Solution {
        public List<Integer> partitionLabels(String S) {
            int len = S.length();
            char[] arr = S.toCharArray();
            int cur = 0, last = 0, temp = 0, count = 0;
            Map<Character, Integer> map = findLast(arr);
            List<Integer> result = new ArrayList<>();
            while(cur < len){
                last = map.get(arr[cur]);
                temp = cur;
                while(temp < last){
                    last = Math.max(last, map.get(arr[++temp]));
                }
                result.add(last - cur + 1);
                cur = last + 1;
            }
            return result;
        }
        private Map<Character, Integer> findLast(char[] arr){
            Map<Character, Integer> map = new HashMap<>();
            for(int i = arr.length - 1; i >= 0; i--){
                if(map.containsKey(arr[i])) continue;
                map.put(arr[i], i);
            }
            return map;
        }
    }