代码随想录——划分字母区间(Leetcode763)

题目链接

贪心

java 复制代码
class Solution {
    public List<Integer> partitionLabels(String s) {
        int[] count = new int[27];
        Arrays.fill(count,0);
        // 统计元素最后一次出现的位置
        for(int i = 0; i < s.length(); i++){
            count[s.charAt(i) - 'a'] = i;
        }
        List<Integer> res = new ArrayList<Integer>();
        int left = 0;
        int right = 0;
        for(int i = 0; i < s.length(); i++){
            // 找到字符出现的最远边界
            right = Math.max(right, count[s.charAt(i) - 'a']);
            if(i == right){
                // 将符合条件的字符串长度插入res
                res.add(right - left + 1);
                left = i + 1;
            }
        }
        return res;
    }
}
相关推荐
魏 无羡5 小时前
webclient
java·webclient
神仙别闹5 小时前
基于 C++ 实现两个有序链表序列的交集
java·c++·链表
swordbob6 小时前
ReentrantLock 与 AQS 完整学习手册
java·开发语言
政企项目老覃7 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
淡海水7 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
m0_587383007 小时前
全民健身解决方案软件开发实战:从架构设计到落地指南
java·spring boot·spring·架构·需求分析
白山编程大哥7 小时前
Java OutputStreamWriter 详解:从字符到字节的桥梁
java·开发语言·python
hansang_IR7 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵8 小时前
MATLAB-matlab基础知识
学习·算法·matlab