https://leetcode-cn.com/problems/partition-labels/description/
A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like “ababcbacadefegde”, “hijhklij” is incorrect, because it splits S into less parts.
Note:
S will have length in range [1, 500].
S will consist of lowercase letters (‘a’ to ‘z’) only.
思路:将字符串S中字符最后出现的位置写入map< char, int> , key为字符,value为最后位置.从0开始向后遍历整个串.
class Solution {
public:
vector<int> partitionLabels(string S) {
vector<int> res; //输出
map<char, int> last_map; //字符最后出现位置的map
for (int i = 0; i < S.size(); i++) {
last_map[S[i]] = i; //构造map
}
//从0开始遍历到串末,[start,last]部分为一段划分
for (int start = 0; start < S.size(); start++) {
int last = last_map[S[start]]; //last初始化
for (int i = start; i <= last; i++) { //遍历[start,last]直接的字符,检查是否有新的last
if (last_map[S[i]] > last) { //若map中存在比当前last还要靠后的记录,更新last
last = last_map[S[i]];
}
}
res.push_back(last-start+1); //检查last完成后,得到一段划分,将结果写入
start = last; //更新start
}
return res;
}
};
py:
注意,与c++不同,py中for循环的i和range()范围是不会在循环中更改的,只能改用while循环
class Solution:
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
res = []
last_map = {}
for i in range(len(S)):
last_map[S[i]] = i
print(last_map)
start = 0
while start < len(S):
last = last_map[S[start]]
i = start
while i <= last:
if last_map[S[i]] > last:
last = last_map[S[i]]
i += 1
res.append(last-start+1)
start = last
start += 1
return res