力扣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 和 lasts.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;
    }
}
相关推荐
鹿角片ljp4 小时前
LeetCode 46. 全排列|吃透回溯
算法·leetcode·职场和发展
鼎艺创新科技4 小时前
不依赖 UE/Unity:我们如何从零搭建一套国产三维 GIS 渲染引擎
人工智能·算法·unity·游戏引擎·三维电子沙盘
程序员三藏5 小时前
Python+requests实现接口自动化测试
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
.道阻且长.6 小时前
11.LeetCode算法习题讲解--滑动窗口--将x减到0的最小操作数
算法·leetcode·职场和发展
wenyq77 小时前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
.格子衫.8 小时前
032动态规划之区间DP——算法备赛
算法·动态规划
青 春 记 忆8 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
小欣加油8 小时前
leetcode3069 将元素分配到两个数组中I
数据结构·c++·算法·leetcode·职场和发展
不会代码的小猴8 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json
怪奇云呼军9 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频