Partition Labels

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.

Idea: Scan twice, record the last position of each char in the first pass, and the second time, see if the last position of char is greater than maxend, and update if it is larger, otherwise if i == maxend indicates that from start to maxend A valid string, then start = i + 1 and so on;

Mainly it is more difficult to record the last char, and then it is more difficult to update the last maxend, the rest is the idea of ​​two pointers;

class Solution {
    public List<Integer> partitionLabels(String S) {
        List<Integer> list = new ArrayList<Integer>();
        if(S == null || S.length() == 0) {
            return list;
        }
        HashMap<Character, Integer> hashmap = new HashMap<>();
        for(int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            // store last position of this char;
            hashmap.put(c, i);
        }
        int start = 0; 
        int maxend = 0;
        for(int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            if(hashmap.get(c) > maxend) {
                maxend = hashmap.get(c);
            }
            if(i == maxend) {
                list.add(maxend - start + 1);
                maxend = 0;
                start = i + 1;
            }
        }
        return list;
    }
}

 

Published 710 original articles · Like 13 · Visits 190,000+

Guess you like

Origin blog.csdn.net/u013325815/article/details/105527226