LeetCode 763、划分字母区间

题目

给你一个字符串 s 。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。例如,字符串 "ababcc" 能够被分为 ["abab", "cc"],但类似 ["aba", "bcc"]["ab", "ab", "cc"] 的划分是非法的。

注意,划分结果需要满足:将所有划分结果按顺序连接,得到的字符串仍然是 s

返回一个表示每个字符串片段的长度的列表。

思路:本质合并区间

代码

java 复制代码
class Solution {
    public List<Integer> partitionLabels(String s) {
        char[] ch = s.toCharArray();
        int n = ch.length;
        int[] last = new int[26];
        for (int i = 0; i < n; i++) {
            last[ch[i] - 'a'] = i;
        }
        List<Integer> ans = new ArrayList<>();
        int start = 0;
        int end = 0;
        for (int i = 0; i < n; i++) {
            end = Math.max(end, last[ch[i] - 'a']);
            if (i == end ) {
                ans.add(i - start + 1);
                start = end + 1;
            }
        }
        return ans;
    }
}

性能

相关推荐
Wang's Blog2 小时前
PostgreSQL笔记49:向量检索核心算法、索引调优与过滤策略深度解析
笔记·算法·postgresql
疯狂打码的少年2 小时前
【数据结构】交换类排序:冒泡与快速排序
数据结构·笔记·算法·排序算法
Nil2082 小时前
leetcode 108有序数组转换为二叉搜索树
数据结构·算法·leetcode
高频因子挖掘机2 小时前
QuantDash 成交量单位统一实战:从“手”到“股”的跨市场量化数据清洗全流程
后端·算法·github
Escalating_xu2 小时前
【C++ STL简介】从六大组件到容器、迭代器与算法协作
java·c++·算法
纪念 2293 小时前
算法二叉树(一)
算法
疯狂打码的少年3 小时前
【数据结构】哈希表:构造与冲突处理
数据结构·笔记·哈希算法·散列表
liulilittle3 小时前
llmx 学习手册 06 —— CPU 指令集优化(AVX-512 三层演进)
c++·学习·算法·ai·llm
土司大王4 小时前
LeetCode hot100——相交链表
算法·leetcode·链表