[LeetCode] Partition String

3597. Partition String

Given a string s, partition it into unique segments according to the following procedure:

  • Start building a segment beginning at index 0.
  • Continue extending the current segment character by character until the current segment has not been seen before.
  • Once the segment is unique, add it to your list of segments, mark it as seen, and begin a new segment from the next index.
  • Repeat until you reach the end of s.

Return an array of strings segments, where segments[i] is the ith segment created.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<string> partitionString(string s) {
string p = "";
unordered_set<string> us;
vector<string> res;
auto push = [&](string& s) {
if(us.count(s)) return;
us.insert(s);
res.push_back(s);
s = "";
};
for(int i = 0; i < s.length(); i++) {
p.push_back(s[i]);
push(p);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/06/29/PS/LeetCode/partition-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.