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

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    又是index从0开始,长度不够因此需要加1

    [思维问题]:

    知道是前向指针,但是不知道怎么确定前面的i:存map[26],然后i顺着循环一遍就行了

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [一句话思路]:

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    不知道last怎么时候保持最大:math.max也是记忆化搜索的一种方式

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    确定前面的i:存map[26],然后i顺着循环一遍就行了

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [算法思想:迭代/递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

     [潜台词] :

    class Solution {
        public List<Integer> partitionLabels(String S) {
            //initialization: result, int[26]
            List<Integer> result = new ArrayList<Integer>();
            int[] map = new int[26];
            
            //store the last position into the map
            for (int i = 0; i < S.length(); i++) {
                map[S.charAt(i) - 'a'] = i;
            }
            
            //for loop: get the last, add last - start, reset start
            int start = 0;
            int last = 0;
            for (int i = 0; i < S.length(); i++) {
                //get the last
                last = Math.max(last, map[S.charAt(i) - 'a']);
                //add last - start, reset start
                if (i == last) {
                    result.add(last - start + 1);
                    start = last + 1;
                }
            }
            
            //return
            return result;
        }
    }
    View Code
  • 相关阅读:
    maven项目的导包问题,已经加载jar包了可是idea检测不到
    spark MLlib矩阵四则运算,线性代数
    maven spark Scala idea搭建maven项目的 pom.xml文件配置
    tensorflow2.0 numpy.ndarray 与tenor直接互转
    TensorFlow2.0矩阵与向量的加减乘
    Ubuntu14.04下Nginx反向代理Odoo域名
    Geforce experience报错:something went wrong try restarting geforce
    github的代码上传成功但是不显示绿格子(一直拖....心痛的教训.....)
    mapper文件提示:No data sources are configured to run this sql
    Pycharm中SQL语句提示SQL Dialect is Not Configured
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9416484.html
Copyright © 2011-2022 走看看