美文网首页
Leetcode 精选之贪心思想(划分字母区间)

Leetcode 精选之贪心思想(划分字母区间)

作者: Kevin_小飞象 | 来源:发表于2020-03-27 15:24 被阅读0次

题目描述

字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。

示例 1:

输入: S = "ababcbacadefegdehijhklij"
输出: [9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。

注意:

S的长度在[1, 500]之间。
S只包含小写字母'a'到'z'。

题目链接:力扣

解题思路

import java.util.*;
public class Main {
    
    public static void main(String[] args) {
        String s = "ababcbacadefegdehijhklij";
        
        List list = partitionLabels(s);
        printList(list);
       
    }

    public static List<Integer> partitionLabels(String S) {
        int[] lastIndexsOfChar = new int[26];
        for (int i = 0; i < S.length(); i++) {
            lastIndexsOfChar[char2Index(S.charAt(i))] = i;
        }
        List<Integer> partitions = new ArrayList<>();
        int firstIndex = 0;
        while (firstIndex < S.length()) {
            int lastIndex = firstIndex;
            for (int i = firstIndex; i < S.length() && i <= lastIndex; i++) {
                int index = lastIndexsOfChar[char2Index(S.charAt(i))];
                if (index > lastIndex) {
                    lastIndex = index;
                }
            }
            partitions.add(lastIndex - firstIndex + 1);
            firstIndex = lastIndex + 1;
        }
        return partitions;
    }

    public static int char2Index(char c) {
        return c - 'a';
    }
    
    public static void printList(List list) {
        //方法1
        for(int i = 0;i < list.size();i++){
            System.out.print(list.get(i) + " ");
        }
    }
}

测试结果

image.png

相关文章

网友评论

      本文标题:Leetcode 精选之贪心思想(划分字母区间)

      本文链接:https://www.haomeiwen.com/subject/lqwluhtx.html