• 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.
    

    Note:

    1. S will have length in range [1, 500].
    2. S will consist of lowercase letters ('a' to 'z') only.
    给出一个小写字母的字符串S.我们想把这个字符串分成尽可能多的部分,这样每个字母最多只出现一个部分,并返回一个表示这些部分大小的整数列表。

    1. /**
    2. * @param {string} S
    3. * @return {number[]}
    4. */
    5. var partitionLabels = function (S) {
    6. let posDict = {};
    7. for (let i = 0; i < S.length; i++) {
    8. let char = S[i];
    9. if (posDict[char]) {
    10. posDict[char].end = i;
    11. } else {
    12. posDict[char] = { start: i, end: i };
    13. }
    14. }
    15. let res = [];
    16. let min = max = 0;
    17. for (let i in posDict) {
    18. let start = posDict[i].start;
    19. let end = posDict[i].end;
    20. if (start > max) {
    21. res.push(max - min + 1);
    22. [min, max] = [start, end];
    23. } else {
    24. max = Math.max(max, end);
    25. }
    26. }
    27. res.push(max - min + 1);
    28. return res;
    29. };
    30. let S = "ababcbacadefegdehijhklij";
    31. let res = partitionLabels(S);
    32. console.log(res);





  • 相关阅读:
    private SortedDictionary<string, object> Dic_values = new SortedDictionary<string, object>();
    [Luogu 2817]宋荣子的城堡
    [测试题]等效集合
    [SDOI 2009]HH去散步
    [HNOI 2013]比赛
    [SCOI 2016]背单词
    [测试题]圆圈
    [Luogu 3389]【模板】高斯消元法
    [Codeforces 505C]Mr. Kitayuta, the Treasure Hunter
    [Codeforces 448C]Painting Fence
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/8290347.html
Copyright © 2020-2023  润新知