-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0691_minStickers.cc
103 lines (100 loc) · 2.2 KB
/
Problem_0691_minStickers.cc
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
94
95
96
97
98
99
100
101
102
103
#include <algorithm>
#include <queue>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;
// TODO: figure it out.
// @sa https://www.bilibili.com/video/BV1Dw411w7P5/
class Solution
{
public:
int minStickers(vector<string>& stickers, string target)
{
vector<vector<string>> graph(26);
unordered_set<string> visited;
for (auto& str : stickers)
{
// 贴纸排序不影响结果
std::sort(str.begin(), str.end());
// 建图,当前贴纸能搞定多少字符
for (int i = 0; i < str.length(); i++)
{
// 过滤重复
if (i == 0 || str[i] != str[i - 1])
{
// graph[c] 表示能搞定字符 c 的贴纸
graph[str[i] - 'a'].push_back(str);
}
}
}
// 排序不影响结果
std::sort(target.begin(), target.end());
visited.emplace(target);
queue<string> que;
que.push(target);
int level = 1;
// 使用队列的形式是整层弹出
while (!que.empty())
{
int size = que.size();
for (int i = 0; i < size; i++)
{
string cur = que.front();
que.pop();
// 检查哪些贴纸可以搞定首字符
for (auto& s : graph[cur[0] - 'a'])
{
// cur = "aabccff"
// s = "accccfkk"
// next = "abf"
// 用 s 贴纸搞定 cur 里的字符,还剩余的字符next
string next = getNext(cur, s);
if (next.empty())
{
// 目标达成
return level;
}
else if (!visited.count(next))
{
visited.emplace(next);
que.push(next);
}
}
}
level++;
}
return -1;
}
// t = "aabccff"
// s = "accccfkk"
// next = "abf"
string getNext(string& t, string& s)
{
string ans;
for (int i = 0, j = 0; i < t.length();)
{
if (j == s.length())
{
ans.push_back(t[i++]);
}
else
{
if (t[i] < s[j])
{
ans.push_back(t[i++]);
}
else if (t[i] > s[j])
{
j++;
}
else
{
i++;
j++;
}
}
}
return ans;
}
};