C++ 将相邻的子字符串分组并查找计数

C++ 将相邻的子字符串分组并查找计数,c++,c,C++,C,嗨,这是我在采访中被要求用C/C++编写代码的一个问题 给定一个字符串,将为您提供可能的操作。 我们可以将相邻的子串分组,例如ABCABCBC可以压缩为 2ABC1BC或1ABCA2BC 在所有可能的选项中,任务是找到长度最小的结果字符串 如果有多个解决方案,则返回按字典顺序排列的最小字符串。 因此,对于上述示例,解决方案为2ABC1BC 另一个例子是 弗拉夫 解决方案:1FLF3LAF 我知道可以使用后缀树或排列/递归方法来完成,但无法获得如何实现的逻辑。请提供帮助?压缩输入前缀并在其余输入上

嗨,这是我在采访中被要求用C/C++编写代码的一个问题

给定一个字符串,将为您提供可能的操作。 我们可以将相邻的子串分组,例如ABCABCBC可以压缩为 2ABC1BC或1ABCA2BC

在所有可能的选项中,任务是找到长度最小的结果字符串

如果有多个解决方案,则返回按字典顺序排列的最小字符串。 因此,对于上述示例,解决方案为2ABC1BC

另一个例子是 弗拉夫 解决方案:1FLF3LAF


我知道可以使用后缀树或排列/递归方法来完成,但无法获得如何实现的逻辑。请提供帮助?

压缩输入前缀并在其余输入上递归调用自身的算法可以做到这一点():

#包括
#包括
#包括
#包括
使用名称空间std;
//确定特定长度的前缀在输入中重复的次数
整数重复(字符串常量和输入,整数前缀长度)
{
int i=1;
当(

(i+1)*prefix_length欢迎来到Stack Overflow!请展示您迄今为止的研究/调试工作。请先阅读页面。编辑您的帖子,不要添加带有注释的信息和代码。我确实删除了所有注释,我是Stack Overflow的新手,所以如果有任何错误,请原谅。谢谢,你可以参考基本信息,算法是如何运行的作品
#include <iostream>
#include <string>
#include <limits>
#include <cstring>
using namespace std;

// determine how many times the prefix of specific length is repeated in the input
int repetitions(string const & input, int prefix_length)
{
    int i = 1;
    while (
        (i + 1) * prefix_length <= input.size() && 
        memcmp(input.data(), input.data() + i * prefix_length, prefix_length) == 0
        )
    {
        ++i;
    }

    return i;
}

// recursively compress input and return compressed string
string compress(string const & input)
{
    // recursion termination
    if (input.empty())
        return string();

    string best;
    int best_length = numeric_limits<int>::max();

    // try various prefix lengths
    for (int prefix_length = 1; prefix_length <= input.length(); ++prefix_length)
    {
        const auto max_count = repetitions(input, prefix_length);

        // try various number of repetitions up to the maximum possible
        for (int count = 1; count <= max_count; ++count)
        {
            // the candidate is compressed prefix and the rest of input compressed recursively
            const auto current = 
                to_string(count) + input.substr(0, prefix_length) + // compressed prefix
                compress(input.substr(prefix_length * count)); // the rest of input compressed recursively

            // store candidate if it is better than the currently best
            if (current.length() < best_length)
            {
                best = current;
                best_length = current.length();
            }
        }
    }

    return best;
}

int main() 
{
    string input;
    cin >> input;
    cout << compress(input);
    return 0;
}