LeetCode.763 Partition Labels(标签分类)

1.题目

You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.

Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.

Return a list of integers representing the size of these parts.

2.样例

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.

Example 2:

Input: s = "eccbbbbdec"
Output: [10]

Constraints:

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

3.题解        

- 根据题目意思,我们需要对一个仅包含小写字母的字符串进行分割,分割的原则:尽量将相同的字符分到一组,并且保证分组数量尽可能多。最后输出最多分组数量的每段的长度。

- 思路:典型的贪心+数组记录下标解法,我们首先遍历数组各个字符最后出现的index,然后利用贪心每次对需要判断的字符判断其最远出现的下标是否大于当前分组里面最大的下标:

        - 1.如果当前字符下标index大于前面分组出现最大的下标,说明该字符不属于前面一组,可以进行切分。

        - 2.如果当前字符的下标小于前面分组出现的最大的下标,说明该字符属于前面同一组。

        - 3.如果当前字符的下标小于前面分组,但是其最后存在的下标大于前面分组的最大下表,则说明该组长度可以继续延长。

        - 4.ps:这里要尤其注意只出现一个字符,和处理到最后一个字符的处理。

- 代码:

class Solution {
    public List<Integer> partitionLabels(String s) {
       // 思路:利用贪心进行字符串切割,每次判断当前下标元素可到达最远距离,如果当前可达到最远距离,则更新最大的,否则如果当前下标index大于之前可到达的最远的maxIndex,则认为是新的一段开始
        if (s == null || s.length() == 0) {
            return new ArrayList<>();
        }

        
        int[] lastIndex = new int[256];
        char[] chs = s.toCharArray();
        for (int i = 0; i < chs.length; i++) {
            lastIndex[chs[i]] = i;
        }

        List<Integer> splitLengthList = new ArrayList<>();
        int curMaxIndex = lastIndex[chs[0]];
        int startIndex=0;
        for (int i = 0; i < chs.length; i++) {
            char curChar = chs[i];
            int curCharLastIndex = lastIndex[curChar];
            if (curCharLastIndex < curMaxIndex) {
                continue;
            }

            // 判断是否为新的开始
            if (i > curMaxIndex) {
                curMaxIndex = curCharLastIndex;
                splitLengthList.add(i-startIndex);
                startIndex=i;
            } else {
                curMaxIndex = Math.max(curMaxIndex, curCharLastIndex);
            }
            
            // 最后一个字符
            if (i == chs.length - 1) {
                splitLengthList.add(i-startIndex+1);
            }
        }
        return splitLengthList;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值