All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0701_0800.s0763_partition_labels.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0701_0800.s0763_partition_labels;

// #Medium #Top_100_Liked_Questions #String #Hash_Table #Greedy #Two_Pointers
// #Data_Structure_II_Day_7_String #Big_O_Time_O(n)_Space_O(1)
// #2022_03_26_Time_1_ms_(100.00%)_Space_40.3_MB_(98.19%)

import java.util.ArrayList;
import java.util.List;

/**
 * 763 - Partition Labels\.
 *
 * Medium
 *
 * You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
 *
 * 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. 
 *
 * **Example 2:**
 *
 * **Input:** s = "eccbbbbdec"
 *
 * **Output:** [10] 
 *
 * **Constraints:**
 *
 * *   `1 <= s.length <= 500`
 * *   `s` consists of lowercase English letters.
**/
public class Solution {
    public List partitionLabels(String s) {
        char[] letters = s.toCharArray();
        List result = new ArrayList<>();
        int[] position = new int[26];
        for (int i = 0; i < letters.length; i++) {
            position[letters[i] - 'a'] = i;
        }
        int i = 0;
        int prev = -1;
        int max = 0;
        while (i < letters.length) {
            if (position[letters[i] - 'a'] > max) {
                max = position[letters[i] - 'a'];
            }
            if (i == max) {
                result.add(i - prev);
                prev = i;
            }
            i++;
        }
        return result;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy