LeetCode 763. Partition Labels
title:
date: 2022-06-28 16:23:00
tags:
categories: LeetCode
LeetCode 763. Partition Labels (划分字母区间)
题目
链接
https://leetcode.cn/problems/partition-labels/
问题描述
字符串 s 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
示例
输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
提示
S的长度在[1, 500]之间。
S只包含小写字母 'a' 到 'z' 。
思路
首先先遍历一遍,找到每个字母最后出现的位置,之后从开头开始拓展,随时更新字符串中存在的字符的最远位置,为tag,之后,当tag == i的时候,就代表这里可以形成一个最短的符合条件的片段,更新。
复杂度分析
时间复杂度 O(n)
空间复杂度 O(c)
代码
Java
public List<Integer> partitionLabels(String s) {
List<Integer> ans = new ArrayList<>();
int[] word = new int[26];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
word[c - 'a'] = i;
}
int tag = 0;
int index = -1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
tag = Math.max(word[c - 'a'], tag);
if (i == tag) {
ans.add(i - index);
index = i;
}
}
return ans;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)