zoukankan      html  css  js  c++  java
  • [LeetCode] 763. Partition Labels(标签划分)

    Description

    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.

    给一个由小写英文字母构成的字符串 S。现需要将其分成尽可能多的段,使得每个字母最多只出现在其中一段,返回一个整数列表存储每一段的长度。

    Example

    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.

    Solution

    两次遍历,第一次遍历时记录每个字符的 lastIndex,第二次遍历时,根据这个 lastIndex 确定划分区间,代码如下:

    import kotlin.math.max
    
    class Solution {
        fun partitionLabels(S: String): List<Int> {
            // 第一次遍历,存储每个字符的 lastIndex
            val lastIndices = hashMapOf<Char, Int>()
            for ((i, c) in S.withIndex()) {
                lastIndices[c] = i
            }
            // 第二次遍历,根据 lastIndex 确定划分区间
            val result = arrayListOf<Int>()
            var begin = 0
            var end = 0
            for (i in S.indices) {
                // 右区间根据每个字符的 lastIndex 做更新
                end = max(lastIndices[S[i]]?:-1, end)
                if (end == i) {
                    // 如果右区间刚好是 i,说明这之前的所有字符只出现在这一个区域
                    // 加入结果集,开始新一轮遍历
                    result.add(end - begin + 1)
                    begin = end + 1
                }
            }
            return result
        }
    }
    
  • 相关阅读:
    MYsql 主从复制
    linux下修改apache,nginx服务端口号
    nginx的安装
    oracle启动流程
    openfire源码编译后部署到linux
    openfire重新配置数据库oracle、mysql
    spark安装和登陆配置
    Linux下安装Openfire 4.2.1
    mac toad下建表问题
    linux 下使用exp/imp 或者expdp/impdp导出导入oracle数据表数据
  • 原文地址:https://www.cnblogs.com/zhongju/p/13862262.html
Copyright © 2011-2022 走看看