代码随想录——划分字母区间(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;
    }
}
相关推荐
回敲代码的猴子12 小时前
2月14日打卡
算法
TimberWill12 小时前
SpringBoot整合Srping Security实现权限控制
java·spring boot·后端
blackicexs12 小时前
第四周第七天
算法
期末考复习中,蓝桥杯都没时间学了13 小时前
力扣刷题19
算法·leetcode·职场和发展
Renhao-Wan13 小时前
Java 算法实践(四):链表核心题型
java·数据结构·算法·链表
踩坑记录14 小时前
递归回溯本质
leetcode
zmzb010314 小时前
C++课后习题训练记录Day105
开发语言·c++·算法
_codemonster14 小时前
JavaWeb开发系列(六)JSP基础
java·开发语言
得一录14 小时前
AI面试·高难度题
人工智能·面试·职场和发展
万邦科技Lafite14 小时前
淘宝店铺所有商品API接口实战指南
java·数据库·mysql