当前位置:网站首页>leetcode刷题笔记 763.划分字母区间(中等)
leetcode刷题笔记 763.划分字母区间(中等)
2022-07-29 05:24:00 【露忆丶十二】
1.题目:
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
示例:
输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
2.代码:
class Solution {
public:
vector<int> partitionLabels(string s) {
int last[26];
int length = s.size();
//找到每个字符最后出现的位置
for(int i = 0; i < length; ++i){
last[s[i] - 'a'] = i;
}
int start =0, end = 0;
vector<int> sss; //存储划分的数据
for(int i = 0; i < length; ++i){
end = max(end, last[s[i] - 'a']);
if(end == i){
sss.push_back(end-start+1);
start = end + 1;
}
}
return sss;
}
};3.解题思路:
输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
结合着上面的例子来看!!
同一个字母只能出现在同一个片段中,还要划分出尽量多的字符串数量,那么每个字母最后一次出现的位置,就有可能是划分字符串的位置,(例子中两次划分的位置是a和e最后出现的位置)在遍历字符串的过程中,通过比对已经遍历的字符最后出现的位置,位置最靠后的一定是截取端,(比如第一个字符串中,字母a的最后出现的位置是s[8],s[0]到s[8]之间包含的字母最后出现的位置都在s[8]之前)并且前一个字符串的结尾是下一个字符串的开头(s[8]是第一个字符串的结尾,s[9]是下一个字符串的开头)。
4.代码:
@第一步:找到每个字符最后出现的位置,存储在一个数组中。
@第二步:定义两个int类型变量start和end,初值均为0,start用于存储字符串的开头,end用于存储已经遍历到的字符串的最远结尾。每遍历一个字符就更新end的值,当end值恰好是当前遍历的位置时,到了截取字符串的位置,那么截取的长度就是end - start + 1,然后把(end + 1)赋值给start,重复操作即可。
边栏推荐
- Hal library learning notes-11 I2C
- Huawei cloud 14 day Hongmeng device development -day3 kernel development
- FT232替代GP232RL USB-RS232转换器芯片国产化应用
- 抽象封装继承多态
- Multithreading and concurrency
- NFC双向通讯13.56MHZ非接触式阅读器芯片--Si512替代PN512
- Hal library learning notes - 8 use of serial communication
- 基于AD9850的多功能信号发生器
- 从头安装MYSQL(MYSQL安装文档-解压版)
- 倾角传感器用于通信铁塔、高压电塔长期监测
猜你喜欢
随机推荐
Hal library learning notes-14 ADC and DAC
Jingwei Qili: OLED character display based on hmep060 (and Fuxi project establishment demonstration)
FT232替代GP232RL USB-RS232转换器芯片国产化应用
Multithreading and concurrency
Ml8 self study notes LDA principle formula derivation
八大排序-----------------堆排序
FPGA based: multi-target motion detection (hand-in-hand teaching ①)
SimpleFOC调参1-力矩控制
Hal library learning notes - 8 use of serial communication
shell工具finalShell
QT learning notes QtSql
低成本2.4GHz 无线收发芯片--Ci24R1
QT learning notes - Import and export of Excel
滑动窗口 Leetcode 76.最小覆盖子串(困难) 76.76. MinimumWindow Substring (Hard)
爬取表情包
mavan中的plugin位置
传统模型预测控制轨迹跟踪——圆形轨迹(功能包已经更新)
SimpleFOC调参3-PID参数整定攻略
IDEA安装scala
NOI Online 2022普及组 题解&个人领悟









