• [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 }
  • 相关阅读:
    mybaits错误解决:There is no getter for property named 'id' in class 'java.lang.String'(转)
    Tomcat配置虚拟路径
    FireFox背景亮度修改
    简单的百度贴吧爬虫实现(urllib)
    python知识总结
    QT-- MainWindow外的cpp文件调用ui
    数据结构--栈的实现
    数据结构-- 队列的实现
    经典排序算法---归并排序
    经典排序算法---希尔排序
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/11124131.html
Copyright © 2020-2023  润新知