2022-4-13 Leetcode763.文字範囲を分割します-[貪欲であることを知っていますが、使用しないでください]

ここに画像の説明を挿入

class Solution {
    
    
    public List<Integer> partitionLabels(String s) {
    
    
        int[] last = new int[26];
        int length = s.length();
        for (int i = 0; i < length; i++) {
    
    
            last[s.charAt(i) - 'a'] = i;
        }
        List<Integer> partition = new ArrayList<Integer>();
        int start = 0, end = 0;
        for (int i = 0; i < length; i++) {
    
    
            end = Math.max(end, last[s.charAt(i) - 'a']);
            //为什么每次都要选择最大的?
            //如果不选择最大的,可能就无法囊括同一个字母出现的全部次数
            if (i == end) {
    
    
                partition.add(end - start + 1);
                start = end + 1;
            }
        }
        return partition;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/partition-labels/solution/hua-fen-zi-mu-qu-jian-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

おすすめ

転載: blog.csdn.net/weixin_51187533/article/details/124139585