代码随想录——划分字母区间(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;
    }
}
相关推荐
蓝色汪洋22 分钟前
xtu oj矩阵
算法
超级大只老咪6 小时前
数组相邻元素比较的循环条件(Java竞赛考点)
java
hh随便起个名6 小时前
力扣二叉树的三种遍历
javascript·数据结构·算法·leetcode
小浣熊熊熊熊熊熊熊丶7 小时前
《Effective Java》第25条:限制源文件为单个顶级类
java·开发语言·effective java
毕设源码-钟学长7 小时前
【开题答辩全过程】以 公交管理系统为例,包含答辩的问题和答案
java·eclipse
啃火龙果的兔子7 小时前
JDK 安装配置
java·开发语言
星哥说事7 小时前
应用程序监控:Java 与 Web 应用的实践
java·开发语言
写写闲篇儿7 小时前
微软面试之白板做题
面试·职场和发展
派大鑫wink7 小时前
【JAVA学习日志】SpringBoot 参数配置:从基础到实战,解锁灵活配置新姿势
java·spring boot·后端
xUxIAOrUIII7 小时前
【Spring Boot】控制器Controller方法
java·spring boot·后端