Skip to content

Commit e8db59b

Browse files
committed
🎉 initial commit for leetcode 763 using find_last_of
1 parent f5cbc85 commit e8db59b

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

C++/763. Partition Labels.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
763. Partition Labels
2+
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.
3+
4+
Example 1:
5+
Input: S = "ababcbacadefegdehijhklij"
6+
Output: [9,7,8]
7+
Explanation:
8+
The partition is "ababcbaca", "defegde", "hijhklij".
9+
This is a partition so that each letter appears in at most one part.
10+
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
11+
Note:
12+
13+
S will have length in range [1, 500].
14+
S will consist of lowercase letters ('a' to 'z') only.
15+
16+
题目大意:给出一个小写字母的字符串S. 我们想把这个字符串分成尽可能多的部分,这样每个字母最多只出现一个部分,并返回一个表示这些部分大小的整数列表。
17+
分析:遍历字符串,找到S[i]在S中最后一次出现的位置标记为end,end位置是当前要切割的字串部分最短的结尾处,当i == end时候说明start~end可以组成一个最短部分串,将这个部分串的长度(end - start + 1)放入ans数组中,然后将start标记为下一个部分串的开始(end+1),最后返回ans数组~
18+
19+
class Solution {
20+
public:
21+
vector<int> partitionLabels(string S) {
22+
vector<int> ans;
23+
for (int i = 0, start = 0, end = 0; i < S.length(); i++) {
24+
end = max(end, (int)S.find_last_of(S[i]));
25+
if (i == end) {
26+
ans.push_back(end - start + 1);
27+
start = end + 1;
28+
}
29+
}
30+
return ans;
31+
}
32+
};

0 commit comments

Comments
 (0)