码迷,mamicode.com
首页 > 其他好文 > 详细

763. Partition Labels 分区标签

时间:2018-01-16 01:02:59      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:ret   ola   min   inpu   note   ring   flow   end   function   

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 分区标签

标签:ret   ola   min   inpu   note   ring   flow   end   function   

原文地址:https://www.cnblogs.com/xiejunzhao/p/8290347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!