Partition Labels

https://www.lintcode.com/problem/partition-labels/description

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Solution {
    /**
     * @param S: a string
     * @return: a list of integers representing the size of these parts
     */
    public List partitionLabels(String S) {
        // Write your code here
        char[] chars = S.toCharArray();
        Node[] nodes = new Node[26];
        for (int i = 0; i < chars.length; i++) {
            char aChar = chars[i];
            int index = aChar - 'a';
            Node node = nodes[index];
            if (node == null) {
                nodes[index] = new Node(i, i);
            } else {
                node.right = i;
            }
        }
        Arrays.sort(nodes, new Comparator() {
            @Override
            public int compare(Node o1, Node o2) {
                if (o1 == null) {
                    return -1;
                }
                if (o2 == null) {
                    return 1;
                }
                if (o1.left == o2.left) {
                    return o2.right - o1.right;
                }
                return o1.left - o2.left;
            }
        });
        List res = new ArrayList<>();
        for (int i = 1; i < nodes.length; i++) {
            Node node = nodes[i];
            Node last = nodes[i - 1];
            if (last == null) {
                continue;
            }
            if (node.left > last.right) {
                res.add(last.right - last.left + 1);
            } else {
                node.left = last.left;
                node.right = Math.max(last.right, node.right);
            }
            if (i == nodes.length - 1) {
                res.add(node.right - node.left + 1);
            }
        }
        return res;
    }

    private class Node {
        int left;
        int right;

        public Node(int left, int right) {
            this.left = left;
            this.right = right;
        }
    }
}

你可能感兴趣的:(Partition Labels)