力扣763. 划分字母区间

Problem: 763. 划分字母区间

文章目录

题目描述

思路

1.创建一个名为 last 的数组,用于存储每个字母在字符串 s 中最后出现的位置。然后,获取字符串 s 的长度 len。

2.计算每个字母的最后位置:遍历字符串 s,对于每个字符 s.charAt(i),计算其在字母表中的位置(s.charAt(i) - 'a'),并将其最后出现的位置 i 存储在 last 数组中。

3.初始化分割的起始和结束位置:创建一个名为 pos 的列表,用于存储每个部分的长度。然后,初始化 start 和 end 为0,它们分别表示当前部分的起始和结束位置。

4.计算每个部分的长度:遍历字符串 s,对于每个字符 s.charAt(i),更新 end 为 end 和 last[s.charAt(i) - 'a'] 中的最大值。然后,将 start 设置为 end + 1。

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为字符串s的长度;

空间复杂度:

O ( 1 ) O(1) O(1)

Code

java 复制代码
class Solution {
    /**
     * Partition Labels
     *
     * @param s Given string
     * @return List<Integer>
     */
    public List<Integer> partitionLabels(String s) {
        int[] last = new int[26];
        int len = s.length();
        for (int i = 0; i < len; ++i) {
            last[s.charAt(i) - 'a'] = i;
        }
        List<Integer> pos = new ArrayList<>();
        int start = 0;
        int end = 0;
        for (int i = 0; i < len; ++i) {
            end = Math.max(end, last[s.charAt(i) - 'a']);
            if (i == end) {
                pos.add(end - start + 1);
                start = end + 1;
            }
        }
        return pos;
    }
}
相关推荐
jianfeng_zhu1 天前
整数数组匹配
数据结构·c++·算法
smj2302_796826521 天前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode
LYFlied1 天前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
唯唯qwe-1 天前
Day23:动态规划 | 爬楼梯,不同路径,拆分
算法·leetcode·动态规划
做科研的周师兄1 天前
中国土壤有机质数据集
人工智能·算法·机器学习·分类·数据挖掘
来深圳1 天前
leetcode 739. 每日温度
java·算法·leetcode
LYFlied1 天前
WebAssembly (Wasm) 跨端方案深度解析
前端·职场和发展·wasm·跨端
yaoh.wang1 天前
力扣(LeetCode) 104: 二叉树的最大深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
hetao17338371 天前
2025-12-21~22 hetao1733837的刷题笔记
c++·笔记·算法
醒过来摸鱼1 天前
递归三种分类方法
算法