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
  • 相关阅读:
    Element Form表单验证
    layui table中记住当前页
    Mysql定时任务
    Mysql存储过程
    StringRedisTemplate与redistemplate
    vue路由传值
    背景色渐变(兼容各浏览器)
    用onclick点击框架跳转
    美化滚动条
    图片无缝滚动
  • 原文地址:https://www.cnblogs.com/immjc/p/8290093.html
Copyright © 2011-2022 走看看