当前位置:网站首页>Leetcode (763) -- dividing letter ranges
Leetcode (763) -- dividing letter ranges
2022-06-26 21:55:00 【SmileGuy17】
Leetcode(763)—— Division of alphabet
subject
character string S It's made up of lowercase letters . We're going to divide this string into as many pieces as possible , The same letter can appear in at most one segment . Returns a list representing the length of each string fragment .
Example :
Input :S = “ababcbacadefegdehijhklij”
Output :[9,7,8]
explain :
The result is “ababcbaca”, “defegde”, “hijhklij”.
Each letter appears in at most one segment .
image “ababcbacadefegde”, “hijhklij” The division is wrong , Because the number of segments is small .
Tips :
- S The length of is [ 1 , 500 ] [1, 500] [1,500] Between .
- S Contains only lowercase letters ‘a’ To ‘z’ .
Answer key
The key : Before processing the array, you can count the information ( frequency 、 Number 、 First or last position, etc ) It can reduce the difficulty
Method 1 : greedy
Ideas
Because the same letter can only appear in the same segment , Obviously, the first and last subscript of the same letter must appear in the same segment . So you need to traverse the string , Get the last subscript of each letter .
After getting the last subscript position of each letter , You can use greedy methods to divide a string into as many fragments as possible , The specific methods are as follows .
- Traversing the string from left to right , Maintain the starting subscript of the current fragment while traversing start \textit{start} start And end subscript end \textit{end} end, At the beginning start = end = 0 \textit{start}=\textit{end}=0 start=end=0.
- For each letter accessed c c c, Get the last subscript position of the current letter end c \textit{end}_c endc, The ending subscript of the current clip must not be less than end c \textit{end}_c endc, So make end = max ( end , end c ) \textit{end}=\max(\textit{end},\textit{end}_c) end=max(end,endc).
- When accessing subscripts end \textit{end} end when , End of current fragment access , The subscript range of the current clip is [ start , end ] [\textit{start},\textit{end}] [start,end], The length is end − start + 1 \textit{end}-\textit{start}+1 end−start+1, Adds the length of the current fragment to the return value , Then make start = end + 1 \textit{start}=\textit{end}+1 start=end+1, Keep looking for the next clip .
- Repeat the process , Until the string is traversed .
The above method uses the greedy idea to find the minimum possible ending subscript of each fragment , Therefore, it can be ensured that the length of each segment must be the shortest length that meets the requirements , If you take a shorter segment , The same letter must appear in multiple clips . Because the segment taken each time is the shortest segment that meets the requirements , Therefore, the number of fragments obtained is also the largest .
Since the end of each segment access is marked by access to the subscript end \textit{end} end, So for each segment , It can ensure that every letter in the current clip must be in the current clip , It can't appear in other clips , It can ensure that the same letter will only appear in the same segment .
perhaps
- Traverse the string from scratch , And count the last position of each character ;
- Use a variable MaxPos preservation The maximum value in the last occurrence position of the currently scanned character . Then traverse the string again from the beginning , And update the MaxPos Value , If you find the current subscript and MaxPos Equal , The split point is found .
For example, below : Scan first “ababc” Then the scanned characters are ‘a’ ‘b’ ‘c’, The maximum value in the last position , namely MaxPos by 8. When it comes to “def” when , The scanned characters are ‘d’ ‘e’ ‘f’,MaxPos by 15. Because the characters ‘a’ ‘b’ ‘c’ It is already the character of the previous interval , Separated .
Code implementation
Leetcode Official explanation :
class Solution {
public:
vector<int> partitionLabels(string s) {
vector<int> res;
int last[26];
int n = s.size();
for (int i = 0; i < n; i++)
last[s[i]-'a'] = i; // Record each letter in s Last position in
int start = 0, end = 0;
for (int i = 0; i < n; i++){
end = max(end, last[s[i]-'a']);
if (end == i){
res.push_back(end - start + 1);
start = end + 1;
}
}
return res;
}
};
My own :
class Solution {
public:
vector<int> partitionLabels(string s) {
// The general problem is : Find the most intervals , The same letter can only appear in the same interval
// Regarding the starting point and ending point of the same letter as the left and right end points of an interval
// This question translates to : Treat overlapping intervals as the same interval , Get the maximum number of intervals
unordered_map<char, int> letter;
vector<vector<int>> section;
int size = s.size();
for(int n = 0; n < size; n++){
if(letter.count(s[n]) == 0){
section.push_back({
n, n});
letter.emplace(s[n], section.size()-1);
}else section[letter[s[n]]][1] = n;
}
// for(auto& it: letter) cout << it.first << " :" << section[it.second][0] << " " << section[it.second][1] << endl;
// There is no need to sort by left endpoint in ascending order , Because the previous cycle is to save from the left endpoint 0 To size-1 The saved
vector<int> ans;
vector<vector<int>> tmp;
size = section.size();
for(int n = 0; n < size; n++){
// At the beginning or between new areas, it does not overlap with the previous interval , Create a new interval , And calculate the length of the previous interval
if(tmp.empty() || section[n][0] >= (*tmp.rbegin())[1]){
if(!tmp.empty()) ans.push_back((*tmp.rbegin())[1] - (*tmp.rbegin())[0] + 1);
tmp.push_back({
section[n][0], section[n][1]});
}else (*tmp.rbegin())[1] = max((*tmp.rbegin())[1], section[n][1]);
if(n == size-1) ans.push_back((*tmp.rbegin())[1] - (*tmp.rbegin())[0] + 1);
}
return ans;
}
};
Complexity analysis
Time complexity : O ( n ) O(n) O(n), among nn Is the length of the string . You need to traverse the string twice , Record the subscript position of the last occurrence of each letter during the first traversal , During the second traversal, the string is divided .
Spatial complexity : O ( ∣ Σ ∣ ) O(∣\Sigma∣) O(∣Σ∣), among Σ \Sigma Σ Is the character set in the string . In this question , The string contains only lowercase letters , therefore ∣ Σ ∣ = 26 |\Sigma|=26 ∣Σ∣=26.
边栏推荐
- KDD2022 | 基于知识增强提示学习的统一会话推荐系统
- Leetcode(122)——买卖股票的最佳时机 II
- [leetcode]- linked list-2
- 诗尼曼家居冲刺A股:年营收近12亿 红星美凯龙与居然之家是股东
- SAP Spartacus 默认路由配置的工作原理
- vulnhub之dc8
- 指南针能开户炒股吗?安全吗?
- 请问CMS里UniAPP版本中的&ldquo;自定义表单列表如何去掉?
- About appium trample pit: encountered internal error running command: error: cannot verify the signature of (solved)
- Different subsequence problems I
猜你喜欢
![leetcode:710. Random numbers in the blacklist [mapping thinking]](/img/ec/a3faeae6636bc3d0d9536962fdd9af.png)
leetcode:710. Random numbers in the blacklist [mapping thinking]

VB.net类库(进阶版——1)

How to analyze financial expenses

BN(Batch Normalization) 的理论理解以及在tf.keras中的实际应用和总结

Module 5 operation

LabVIEW Arduino tcp/ip remote smart home system (project part-5)

VB.net类库(进阶——2 重载)

Word chess based on heuristic search

leetcode:152. 乘积最大子数组【考虑两个维度的dp】

DLA模型(分类模型+改进版分割模型) + 可变形卷积
随机推荐
Icml2022 | neurotoxin: a lasting back door to federal learning
【图像处理基础】基于matlab GUI图像曲线调整系统【含Matlab源码 1923期】
CVPR 2022 | 美团技术团队精选论文解读
VB.net类库(进阶——2 重载)
leetcode:152. 乘积最大子数组【考虑两个维度的dp】
Final part of web crawler: send directional messages to 100000 Netease cloud users
[mathematical modeling] spanning tree based on Matlab GUI random nodes [including Matlab source code 1919]
矩阵求导及其链式法则
会计要素包括哪些内容
Web crawler 2: crawl the user ID and home page address of Netease cloud music reviews
Usage of MGrid in numpy
Android mediacodec hard coded H264 file (four), ByteDance Android interview
在线协作文档综合评测 :Notion、FlowUs、Wolai、飞书、语雀、微软 Office、谷歌文档、金山文档、腾讯文档、石墨文档、Dropbox Paper、坚果云文档、百度网盘在线文档
Using C to operate SQLSERVER database through SQL statement tutorial
QT环境下配置Assimp库(MinGW编译器)
numpy中mgrid的用法
MATLAB与Mysql数据库连接并数据交换(基于ODBC)
基于启发式搜索的一字棋
Is there any risk in opening a new bond registration account? Is it safe?
网络连接断开请刷新重试