zoukankan      html  css  js  c++  java
  • 0763. Partition Labels (M)

    Partition Labels (M)

    题目

    A string S of lowercase English 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:

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

    题意

    将给定字符串划分成尽可能多的子串,使得同一个字母只出现在一个子串中。

    思路

    主要思想是记录每个字母出现的最后一个位置,得到每个字母的出现区间。对于一个字母的出现区间S,如果其中有字母的结束位置大于S的右端点,那么需要更新右端点,直到右端点对应字母的结束位置就是右端点本身,这样就找到了一个符合条件的子串。


    代码实现

    Java

    class Solution {
        public List<Integer> partitionLabels(String S) {
            List<Integer> ans = new ArrayList<>();
            int[] ends = new int[26];
            for (int i = 0; i < S.length(); i++) {
                char c = S.charAt(i);
                ends[c - 'a'] = Math.max(ends[c - 'a'], i);
            }
            int start = 0, end = 0;
            for (int i = 0; i < S.length(); i++) {
                char c = S.charAt(i);
                end = Math.max(end, ends[c - 'a']);
                if (end == i) {
                    ans.add(end - start + 1);
                    start = i + 1;
                }
            }
            return ans;
        }
    }
    
  • 相关阅读:
    stm32 同步NTP服务器的时间
    WPF 好看的UI库和图表库介绍
    JS知识点及面试常规复习
    wordpress本地安装教程
    apache window 上的安装
    GD32F303 驱动 W25Q64
    芯茂微开关电源 LP3667B 5W极简高性能PSR --满足全球认证要求
    开发工具
    缓存雪崩、缓存穿透、缓存击穿、缓存预热、缓存降级
    c# Monitor.wait() 和sleep的区别
  • 原文地址:https://www.cnblogs.com/mapoos/p/13617247.html
Copyright © 2011-2022 走看看