forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind-the-string-with-lcp.cpp
More file actions
32 lines (31 loc) · 922 Bytes
/
Copy pathfind-the-string-with-lcp.cpp
File metadata and controls
32 lines (31 loc) · 922 Bytes
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
// Time: O(n^2)
// Space: O(1)
// constructive algorithms, greedy, dp
class Solution {
public:
string findTheString(vector<vector<int>>& lcp) {
string result(size(lcp), 0);
for (int i = 0, curr = 'a'; i < size(lcp); ++i) {
if (result[i]) {
continue;
}
if (curr > 'z') {
return "";
}
for (int j = i; j < size(lcp[0]); ++j) {
if (lcp[i][j]) {
result[j] = curr;
}
}
++curr;
}
for (int i = size(lcp) - 1; i >= 0; --i) {
for (int j = size(lcp[0]) - 1; j >= 0; --j) {
if (lcp[i][j] != (result[i] == result[j] ? (i + 1 < size(lcp) && j + 1 < size(lcp[0]) ? lcp[i + 1][j + 1] + 1: 1): 0)) {
return "";
}
}
}
return result;
}
};