Partition Labels

A string S of lowercase English 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:


Solution:

brute force

class Solution {
    public List<Integer> partitionLabels(String S) {
        List<Set<Character>> list = new ArrayList();
        List<Integer> result = new ArrayList();
        for (char c : S.toCharArray()) {
            boolean duplicate = false;
            for (int i = 0; i < list.size(); i ++) {
                Set<Character> set = list.get(i);
                if (set.contains(c)) {
                    merge(list, result, i);
                    list = list.subList(0, i + 1);
                    result = result.subList(0, i + 1);
                    duplicate = true;
                    break;
                }
            }
            if (!duplicate) {
                list.add(new HashSet());
                result.add(0);
            }
            list.get(list.size() - 1).add(c);
            result.set(result.size() - 1, result.get(result.size() - 1) + 1);
        }
        return result;
    }
    
    private void merge(List<Set<Character>> list, List<Integer> result, int i) {
        for (int j = i + 1; j < list.size(); j ++) {
            list.get(i).addAll(list.get(j));
            result.set(i, result.get(j) + result.get(i));
        }
    }
}

Solution 2:

Two pointer:

  public List<Integer> partitionLabels(String S) {
        Integer[] positions = new Integer[26];
        char[] chs = S.toCharArray ();
        for (int i = 0; i < chs.length; i++)
            positions[chs[i] - 'a'] = i;
        List<Integer> resLs = new ArrayList<> ();
        int pos = 0, end = 0, anchor = 0;
        while (pos < chs.length) {
            end = Math.max (positions[chs[pos] - 'a'], end);
            if (pos == end) {
                resLs.add (pos - anchor + 1);
                anchor = pos + 1;
            }
            pos++;
        }
        return resLs;
    }