【LeetCode】Day110-划分字母区间

本文介绍了一种使用贪心策略解决字符串中字母区间划分的问题,通过记录每个字符最后一次出现的位置,找出包含当前字符的最小区间,并更新区间宽度。时间复杂度为O(n),空间复杂度为O(S)。实例代码演示了如何在Java中实现这一技巧。
摘要由CSDN通过智能技术生成

题目

763. 划分字母区间【中等】

题解

根据提示里的内容可以做出个大半了,中心思想就是贪心

Try to greedily choose the smallest partition that includes the first letter. If you have something like “abaccbdeffed”, then you might need to add b. You can use an map like “last[‘b’] = 5” to help you expand the width of your partition.

class Solution {
    public List<Integer> partitionLabels(String s) {
        int n=s.length();
        List<Integer>res=new ArrayList<>();
        //字符最后出现的位置
        int[] last=new int[26];
        for(int i=0;i<n;i++){
            last[s.charAt(i)-'a']=i;
        }
        int i=0;
        while(i<n){
            int end=last[s.charAt(i)-'a'];
            for(int j=i+1;j<=end;j++){
                end=Math.max(end,last[s.charAt(j)-'a']);
            }
            res.add(end-i+1);
            i=end+1;
        }
        return res;
    }
}

时间复杂度: O ( n ) O(n) O(n),看着是双重循环,但是 i 和 j 其实可以视为一个指针,共同遍历字符串s一次,所以复杂度其实只是O(n)

空间复杂度: O ( S ) O(S) O(S)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值