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

    尽可能多的找出分区,要求每个分区中的每个字母出现次数最多。

    通过Example可以大致了解题目含义。

    贪心算法思路:

    1、使用一个map来存储每个字母出现的最大索引值。

    如例子所示:

    a-8, b-5, c-7, d-14, e-15, f-11, g-13, h-19, i-22, j-23, k-20, l-21

    2、遍历数组,要求在当前字母所包含的分区最大。

    如ababcbaca.

    由map可知,a-8,在索引0-8之间所有字母在map中的最大索引不超过8。所以可以构成一个分区

    这时从索引9开始遍历。d-14,在所有9-14之间的字母中,存在e的最大索引超过了14,所以令分区扩大为9-15。

    剩下的部分按照这个思路遍历即可。

    3、将各分区的大小放去res数组中即可。

    class Solution {
    public:
        vector<int> partitionLabels(string S) {
            vector<int> res;
            unordered_map<char, int> max_pos;
            for (int i = 0; i < S.size(); i++) {
                max_pos[S[i]] = i;
            }
            for (int i = 0; i < S.size();) {
                int beg = i;
                int end = max_pos[S[i]];
                for (int j = i + 1; j < end; j++) {
                    end = max(end, max_pos[S[j]]);
                }
                res.push_back(end - beg + 1);
                i = end + 1;
            }
            return res;
        }
    };
    // 10 ms
  • 相关阅读:
    Java 常见异常种类
    Spring3.2+mybatis3.2+Struts2.3整合配置文件大全
    Java中的基本类型和引用类型变量的区别
    【git】Git 提示fatal: remote origin already exists 错误解决办法
    【Java集合】Java中集合(List,Set,Map)
    POJ3322-经典的游戏搜索问题
    程序人生[流程图]
    不使用中间变量交换两个数
    做人要低调,别把自己太当回事
    【转】嵌套子控件设计时支持
  • 原文地址:https://www.cnblogs.com/immjc/p/8290093.html
Copyright © 2011-2022 走看看