Skip to content

Commit 0814c50

Browse files
authored
Create 763._Partition_Labels.md
1 parent f239e34 commit 0814c50

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# 763. Partition Labels
2+
3+
**<font color=red>难度: Medium</font>**
4+
5+
## 刷题内容
6+
7+
> 原题连接
8+
9+
* https://leetcode.com/problems/partition-labels/description/
10+
11+
> 内容描述
12+
13+
```
14+
15+
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.
16+
17+
Example 1:
18+
Input: S = "ababcbacadefegdehijhklij"
19+
Output: [9,7,8]
20+
Explanation:
21+
The partition is "ababcbaca", "defegde", "hijhklij".
22+
This is a partition so that each letter appears in at most one part.
23+
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
24+
Note:
25+
26+
S will have length in range [1, 500].
27+
S will consist of lowercase letters ('a' to 'z') only.
28+
```
29+
30+
## 解题方案
31+
32+
> 思路 1
33+
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******
34+
35+
36+
从第一个字母开始,只要我们包含了这个字母,那么它在S中出现的最后一次我们也要包含进去,当前出现过的所有的字母,我们每次都要更新最后出现的那一次,
37+
并且要一直遍历到其最后一次,这样我们可以维护一个当前至少需要遍历到的end,然后只要出现一个新的字母,
38+
就更新一个这个end(取新字母最后出现idx和end之间的大者),最后,当我们遍历到一个idx的时候,如果这个idx与我们的end相等,
39+
说明截止当前所有出现的字母都在我们的[start, end]字串当中了,直接append它的长度到res中,一直遍历到最后,返回res
40+
41+
beats 98.39%
42+
43+
```python
44+
class Solution(object):
45+
def partitionLabels(self, S):
46+
"""
47+
:type S: str
48+
:rtype: List[int]
49+
"""
50+
if not S or len(S) == 0:
51+
return True
52+
lookup = {}
53+
for i, c in enumerate(S):
54+
lookup[c] = i
55+
start, end, res = 0, 0, []
56+
for i, c in enumerate(S):
57+
end = max(end, lookup[c])
58+
if i == end:
59+
res.append(end-start+1)
60+
start = i + 1
61+
return res
62+
```
63+
64+
65+
66+
67+
68+
69+
70+
71+
72+
73+
74+
75+
76+

0 commit comments

Comments
 (0)