-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path763. Partition Labels.cpp
More file actions
59 lines (52 loc) · 1.92 KB
/
763. Partition Labels.cpp
File metadata and controls
59 lines (52 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Scans once to record the last index of appearance for each character using an array.
// Scans again to extend the boundary of partitions to the maximum last index of characters that have appeared.
// Once the current index meets the boundary, a partition is formed.
// T: O(n)
// S: O(n)
class Solution {
public:
vector<int> partitionLabels(string s) {
vector<int> res;
if (s.empty()) return res;
vector<int> char_to_last_index(26, 0);
for (int i = 0; i < s.size(); ++i) {
char_to_last_index[s[i] - 'a'] = i;
}
int boundary = 0;
int size = 0;
for (int i = 0; i < s.size(); ++i) {
size += 1;
if (char_to_last_index[s[i] - 'a'] > boundary) boundary = char_to_last_index[s[i] - 'a'];
if (i == boundary) {
res.emplace_back(size);
size = 0;
}
}
return res;
}
};
// from collections import defaultdict
# Uses a hashtable to scan the input once, storing the frequency of each character.
# Scans again to record each character's frequency up to the current index. If all frequencies reach their maximum(total remaining count decreases to 0),
# then this index marks a partition boundary.
// T: O(n)
// S: O(n)
// class Solution:
// def partitionLabels(self, s: str) -> List[int]:
// char_to_freq = defaultdict(int)
// for char in s:
// char_to_freq[char] += 1
// remain_count = 0
// partition_keys = set()
// res = []
// size = 0
// for char in s:
// size += 1
// if char not in partition_keys:
// partition_keys.add(char)
// remain_count += char_to_freq[char]
// remain_count -= 1
// if remain_count == 0:
// res.append(size)
// size = 0
// return res