forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
93 lines (71 loc) · 2.02 KB
/
main2.cpp
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/// Source : https://leetcode.com/problems/brace-expansion/
/// Author : liuyubobobo
/// Time : 2020-05-07
#include <iostream>
#include <vector>
#include <set>
using namespace std;
/// DFS
/// Using vector to store result and sorting at last
/// Time Complexity: O(nlogn)
/// Space Complexity: O(n)
class Solution {
public:
vector<string> expand(string s) {
vector<string> res = expand(s, 0, s.size() - 1);
sort(res.begin(), res.end());
return res;
}
private:
vector<string> expand(const string& s, int l, int r){
if(l > r) return {};
vector<string> a, b;
int i;
if(s[l] == '{'){
for(i = l + 1; i <= r; i ++)
if(s[i] == '}'){
a = split(s, l + 1, i - 1);
break;
}
b = expand(s, i + 1, r);
return mul(a, b);
}
for(i = l; i <= r; i ++)
if(s[i] == '{') break;
a = split(s, l, i - 1);
b = expand(s, i, r);
return mul(a, b);
}
vector<string> mul(const vector<string>& a, const vector<string>& b){
if(a.empty()) return b;
if(b.empty()) return a;
vector<string> res;
for(const string& s1: a)
for(const string& s2: b)
res.push_back(s1 + s2);
return res;
}
vector<string> split(const string& s, int l, int r){
vector<string> res;
for(int start = l, i = start + 1; i <= r + 1; i ++)
if(i == r + 1 || s[i] == ','){
res.push_back(s.substr(start, i - start));
start = i + 1;
i = start;
}
return res;
}
};
void print_vec(const vector<string>& vec){
for(const string& e: vec)
cout << e << " ";
cout << endl;
}
int main() {
print_vec(Solution().expand("{a,b}c{d,e}f"));
// "acdf","acef","bcdf","bcef"
print_vec(Solution().expand("abcd"));
// abcd
print_vec(Solution().expand("k{a,b,c,d,e,f,g}"));
return 0;
}