找到排列的ASCII转换

Find permutations ASCII conversion

本文关键字:ASCII 转换 排列      更新时间:2023-10-16

我正在处理问题集,我无法弄清楚此功能的工作原理。任何帮助将非常感激。主要是我对为什么使用ASCII与" 0"一起感到困惑,并且在将它们投射到ASCII之后的增量和减少。

bool isPermutation(string str1, string str2)
{
    if(str1.size() != str2.size())
        return false;
    int i, j, counts[10];
    for(i = 0; i < 10;i++)
        counts[i] = 0;
    for(i = 0; i < str1.size(); i++)
        counts[str1[i] - '0']++; // (1)
    for(i = 0; i < str1.size(); i++)
        counts[str2[i] - '0']--; // (2)
    for(i = 0; i < 10; i++) // (3)
        if(counts[i] != 0) // (4)
            return true; // (5) Should be return false;
    return false; // (6) Should be return true;
}

您发布的代码不正确。最关键的错误是,正如我在评论中提到的那样,数组counts太小。让我将程序更新为以下内容:

bool isPermutation(std::string a, std::string b) {
    char counts[256] = {0}; // initializes all elements to zero.
    if (a.size() != b.size())
        return false;
    for (int i; i < a.size(); ++i)
        counts[a[i]]++;
    for (int i; i < b.size(); ++i)
        counts[b[i]]--;
    for (int i; i < sizeof(counts) / sizeof(counts[0]); ++i)
        if (counts[i] != 0)
            return false;
    return true;
}

整个想法是计算a中每个字符的实例数;因此,当第一个for -Loop完成后,counts[i]包含每个字母的实例数(value)(index,ascii -valued)。

然后将其降低在第二个for -Loop中。其中不匹配,即所有counts都不为零,那么它不能成为置换。