-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpartition_labels.cpp
More file actions
62 lines (57 loc) · 1.49 KB
/
partition_labels.cpp
File metadata and controls
62 lines (57 loc) · 1.49 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
60
61
62
/*
* =====================================================================================
*
* Filename: partition_labels.cpp
*
* Description: 763. Partition Labels
* https://leetcode.com/problems/partition-labels/
*
* Version: 1.0
* Created: 07/12/2025 22:53:58
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
class Solution {
public:
std::vector<int> partitionLabels(std::string s) {
std::unordered_map<char, int> indexes;
for (int i = 0; i < s.length(); i++) {
indexes[s[i]] = i;
}
std::vector<int> parts;
int prev = -1;
int last = 0;
for (int i = 0; i < s.length(); i++) {
last = std::max(last, indexes[s[i]]);
if (last == i) {
parts.push_back(last - prev);
prev = i;
last = i + 1;
}
}
if (last == s.length() - 1) {
parts.push_back(last - prev);
}
return parts;
}
};
TEST(Solution, partitionLabels) {
std::vector<std::pair<std::string, std::vector<int>>> cases = {
{"ababcbacadefegdehijhklij", {9, 7, 8}},
{"eccbbbbdec", {10}},
};
for (auto& [s, parts] : cases) {
EXPECT_THAT(Solution().partitionLabels(s), testing::ElementsAreArray(parts));
}
}