763. Partition Labels 分区标签

Posted Long Long Journey

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);





以上是关于763. Partition Labels 分区标签的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 763. Partition Labels

[LeetCode] 763. Partition Labels

763. Partition Labels

763. Partition Labels(贪心)

763. Partition Labels

leetcode 763 .Partition Labels 题解