zoukankan      html  css  js  c++  java
  • [LeetCode] 763. 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.
    

    Note:

    1. S will have length in range [1, 500].
    2. S will consist of lowercase letters ('a' to 'z') only.

    题意:尽可能的把一个数组分解成多个,分解原则,相同的字母只能出现在一个数组里

    贪心的典型例子,关键在于每个字母最后出现的位置,每次都更新最大(位置靠后的那个),以那个为界拆就行了

    class Solution {
        public List<Integer> partitionLabels(String S) {
            int[] lastIndex = new int[26];
            for (int i = 0; i < S.length(); i++) {
                lastIndex[S.charAt(i) - 'a'] = i;
            }
            List<Integer> list = new ArrayList<>();
            int i = 0;
            while (i < S.length()) {
                int j = lastIndex[S.charAt(i) - 'a'];
                for (int k = i; k < j; k++) {
                    if (lastIndex[S.charAt(k) - 'a'] > j)
                        j = lastIndex[S.charAt(k) - 'a'];
                }
                list.add(j - i + 1);
                if (j == S.length() - 1)
                    break;
                i = j + 1;
            }
            return list;
        }
    }
  • 相关阅读:
    oracle-DML-2
    Oracle--DML
    jquery 调用asp.net后台代码
    hdu--1505--稍微特别的子矩阵求和<修改第一次发表的错误>--<增加stack写法>
    hdu--2159--二维费用背包<一维错误解法>
    hdu--2571--dp
    hdu--1231&&1003--dp
    hdu--1251--字典树
    hdu--1075--字典树||map
    hdu--1421--dp&&滚动数组
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9823281.html
Copyright © 2011-2022 走看看