力扣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;
    }
}
相关推荐
wy_hhxx42 分钟前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
码途行者1 小时前
每天10分钟学Go:第20课 泛型
c++·算法·golang
AIgorithmGEEK3 小时前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
风落青芜5 小时前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z5 小时前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah6 小时前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
草履虫AI课6 小时前
强化学习从零到一 07|重要性采样:借别人的数据,算自己的期望
算法·强化学习
AAA修煤气灶刘哥7 小时前
明明输入了完整报错,知识库怎么净给我相似答案?
人工智能·后端·算法
凌冰_8 小时前
数据结构 - 渐进符号和递归的复杂度(二)
数据结构·算法·软件工程
Highcharts.js9 小时前
Highcharts 在商业智能中的实战应用:释放数据洞察
前端·人工智能·算法·信息可视化·数据分析·数据可视化·highcharts