代码随想录——划分字母区间(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;
    }
}
相关推荐
spencer_tseng2 小时前
Stream not available [SysDictDataMapper.xml]
xml·java
蒸蒸yyyyzwd6 小时前
cpp对象模型学习笔记1.1-2.8
java·笔记·学习
程序员徐师兄7 小时前
Windows JDK11 下载安装教程,适合新手
java·windows·jdk11 下载安装·jdk11 下载教程
RANCE_atttackkk7 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
数研小生8 小时前
构建命令行单词记忆工具:JSON 词库与艾宾浩斯复习算法的完美结合
算法·json
芒克芒克8 小时前
LeetCode 题解:除自身以外数组的乘积
算法·leetcode
五岳8 小时前
DTS按业务场景批量迁移阿里云MySQL表实战(下):迁移管理平台设计与实现
java·应用·dts
zhougl9968 小时前
Java 所有关键字及规范分类
java·开发语言
Python 老手9 小时前
Python while 循环 极简核心讲解
java·python·算法
@Aurora.9 小时前
优选算法【专题九:哈希表】
算法·哈希算法·散列表