【问题标题】:Adding combine arrays only if value doesn't already exist仅当值不存在时才添加组合数组
【发布时间】:2021-12-03 16:53:47
【问题描述】:

如果我有字符串:

string s1 = "abcabb";
string S2 = "acbcba";

并想将它们添加进去,结果将是:

string s[] = ["aa","bc", "ac", "bb", "ba"]

基于索引组合字符,但仅在对不存在时添加到 s[] 例如"ba" = "ab" 如果发现重复,则将 +1 添加到整数。

对于最大大小为 10⁶ 的大字符串,什么可能是一个相当快的算法或函数。

【问题讨论】:

  • "但仅在对不存在的情况下添加到 s[] 例如 "ba" = "ab" 如果找到重复项,则将 +1 添加到整数。" 您要查找的内容通常称为multiset。例如见cplusplus.com/reference/set/multiset
  • 哦,我不知道那些存在。我会调查的。

标签: c++ string algorithm


【解决方案1】:

您可以使用std::unordered_map 添加std::string 键和int 作为存储该键存在多少的值。您可能需要确保 'a' 'b''b' 'a' 最终都作为同一个键。

例子:

std::string s1 = "abcabb";
std::string s2 = "acbcba";

std::unordered_map<std::string, int> result;

for (size_t index = 0; index < s1.size(); ++index) {
    char c1 = s1[index];
    char c2 = s2[index];
    std::string key = c1 < c2 ? std::string({c1, c2}) : std::string({c2, c1});
    ++result[key];
}

这应该在 O(n) 时间内,因为在 std::unordered_map 中的查找是恒定时间。
请注意,此代码假定两个输入字符串的长度相同。

【讨论】:

  • 您可以在for-loop 之前添加一个简单的检查两个字符串的长度是否相同。
猜你喜欢
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 2016-10-19
  • 2016-09-01
  • 2023-01-09
  • 1970-01-01
  • 2013-12-27
  • 2023-03-19
相关资源
最近更新 更多