Loading

[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
    }
}
posted @ 2020-10-23 09:16  Zhongju.copy()  阅读(101)  评论(0编辑  收藏  举报