当前位置:网站首页>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.
边栏推荐
- Which securities company is the most convenient, safe and reliable for opening an account
- What are the accounting elements
- 【图像处理基础】基于matlab GUI图像曲线调整系统【含Matlab源码 1923期】
- Data governance does everything
- 基于启发式搜索的一字棋
- QT环境下配置Assimp库(MinGW编译器)
- leetcode:710. Random numbers in the blacklist [mapping thinking]
- Leetcode(452)——用最少数量的箭引爆气球
- Godson China Science and technology innovation board is listed: the market value is 35.7 billion yuan, becoming the first share of domestic CPU
- Centos7 compiling and installing redis
猜你喜欢

The latest 2022 research review of "continuous learning, CL"

线性模型LN、单神经网络SNN、深度神经网络DNN与CNN测试对比

【图像处理基础】基于matlab GUI图像直方图均衡化系统【含Matlab源码 1924期】

About appium trample pit: encountered internal error running command: error: cannot verify the signature of (solved)

Shiniman household sprint A shares: annual revenue of nearly 1.2 billion red star Macalline and incredibly home are shareholders
![[solution] sword finger offer 15 Number of 1 in binary (C language)](/img/ab/149775ae8ed94464efdf6921c1022a.png)
[solution] sword finger offer 15 Number of 1 in binary (C language)

API管理之利剑 -- Eolink

诗尼曼家居冲刺A股:年营收近12亿 红星美凯龙与居然之家是股东

卷积神经网络(CNN)详解及TensorFlow2代码实现

Convolutional neural network (CNN) explanation and tensorflow2 code implementation
随机推荐
360 mobile assistant is the first to access the app signature service system to help distribute privacy and security
YOLOv6:又快又准的目標檢測框架開源啦
Different subsequence problems I
Web crawler 2: crawl the user ID and home page address of Netease cloud music reviews
卷积神经网络(CNN)详解及TensorFlow2代码实现
VB.net类库(进阶版——1)
ICML2022 | Neurotoxin:联邦学习的持久后门
在哪家券商公司开户最方便最安全可靠
Word chess based on heuristic search
同花顺注册开户有没有什么风险?安全吗?
证券注册开户有没有什么风险?安全吗?
The latest 2022 research review of "continuous learning, CL"
Configuring assimp Library in QT environment (MinGW compiler)
leetcode:1567. Length of the longest subarray whose product is a positive number [dp[i] indicates the maximum length ending with I]
Usage of MGrid in numpy
关于appium踩坑 :Encountered internal error running command: Error: Cannot verify the signature of (已解决)
Flutter 中 ValueNotifier<List<T>> 监听问题解决
Brief analysis of the self inspection contents of the blue team in the attack and defense drill
Parsing complex JSON in fluent
网易云信正式加入中国医学装备协会智慧医院分会,为全国智慧医院建设加速...