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
        }
    }
    
  • 相关阅读:
    Zigbee学习路线
    Zigbee简介
    验证lagrange 定理
    为什么(12)式,km不能直接相乘?而要让域k先乘一个代数A里面的单位元,再作用在群M上呢?
    strong weak distribution
    sufficient statistics
    tensorflow TypeError: Can not convert a float32 into a Tensor or Operation
    tensorflow 训练的时候loss=nan
    tensorflow run()和 eval()
    python array基本操作一
  • 原文地址:https://www.cnblogs.com/zhongju/p/13862262.html
Copyright © 2011-2022 走看看