中级农民
- 积分
- 106
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2019-9-24
- 最后登录
- 1970-1-1
|
本帖最后由 dfcmichael 于 2022-4-16 23:36 编辑
按dp模版现写了一份,仅供参考,divide conquer把词分成左右两部分,然后dp确保不重查。
(没仔细想corner case。也假设alias不会出现循环,例k1<-key1, k2<-key2, k1k2<-k12, k12<-key1key2)- std::unordered_set<std::string>& findAliasHelper(const std::string& value,
- std::unordered_map<string, string>& aliases,
- std::unordered_map<std::string, std::unordered_set<string>>& dp) {
- if (!dp.count(value)) {
- std::unordered_set<std::string> a, b;
-
- // 存本身和对应的alias
- a.insert(value);
- if (aliases.count(value)) {
- a.insert(aliases[value]);
- }
-
- // 把词分左右两部分,分别找出对应的alias list,然后存组装的
- for (int i = 1; i + 1 < value.size(); ++i) {
- std::string leftWord = value.substr(0, i);
- std::string rightWord = value.substr(i, value.size() - i);
- const auto leftAliases = findAliasHelper(leftWord, aliases, dp);
- const auto rightAliases = findAliasHelper(rightWord, aliases, dp);
- for(auto leftIt : leftAliases) {
- for(auto rightIt : rightAliases) {
- a.insert(leftIt + rightIt);
- }
- }
- }
-
- // 处理除原value外,新生成的alias
- for (auto v : a) {
- if (v != value) {
- auto c = findAliasHelper(v, aliases, dp);
- b.insert(c.begin(), c.end());
- }
- }
- a.insert(b.begin(), b.end());
-
- // 存入dp
- dp[value] = a;
- }
- return dp[value];
- }
- std::unordered_set<string> findAlias(const std::string& value,
- const std::unordered_map<string, string>& aliases) {
- std::unordered_map<std::string, std::unordered_set<string>> dp;
- std::unordered_map<string, string> aliasesMp;
- // 题里alias貌似需要反一下
- for(auto p : aliases) {
- aliasesMp[p.second] = p.first;
- }
- return findAliasHelper(value, aliasesMp, dp);
- }
复制代码- // Test
- const string value{"key1key2key3"};
- std::unordered_map<string, string> aliases({
- {"k1", "key1"},
- {"k2", "key2"},
- {"k12", "k1k2"},
- {"k34", "k12"}
- });
- output: k12key3, k34key3, k1key2key3, k1k2key3, key1k2key3, key1key2key3
复制代码 |
|