zoukankan      html  css  js  c++  java
  • [leetcode]763. Partition Labels 分割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

    题意

    给你一个串, 要求分割尽量多份,使得每份中的字母只在该被分割部分出现

    思路

    扫一遍串,用一个map存每个字母的最大index值

    扫一遍串,lock住start指针,更新即将被分割子串最大的last值,当last == i, 则找到一个被分割子串。 

    代码

     1 class Solution {
     2     public List<Integer> partitionLabels(String S) {
     3         if(S == null || S.length() == 0){return null; }
     4         List<Integer> list = new ArrayList<>();
     5         int[] map = new int[26];  
     6 
     7         for(int i = 0; i < S.length(); i++){
     8             map[S.charAt(i)-'a'] = i;
     9         }
    10         
    11         int last = 0;
    12         int start = 0;
    13         for(int i = 0; i < S.length(); i++){
    14             last = Math.max(last, map[S.charAt(i)-'a']);
    15             if(last == i){
    16                 list.add(last - start + 1);
    17                 start = last + 1;
    18             }
    19         }
    20         return list;
    21     }
    22 }
  • 相关阅读:
    Python语言之并发编程
    python语言之系统工具
    python语言之正则
    python语言之字符串与字节
    Python语言之持久化
    Python语言之数字格式化与时间
    Python语言之异常处理与测试
    Java-AQS源码详解(细节很多!)
    redis的主从复制原理
    Amdahl定律和可伸缩性
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/11124131.html
Copyright © 2011-2022 走看看