找到排列的ASCII转换
Find permutations ASCII conversion
我正在处理问题集,我无法弄清楚此功能的工作原理。任何帮助将非常感激。主要是我对为什么使用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
都不为零,那么它不能成为置换。
相关文章:
- 在C++中使用 ASCII 代码将输入从小写转换为大写
- 我的程序将 26 个字母转换为 ascII 没有显示正确答案
- 我写的 ASCII 到二进制转换器C++向后显示二进制,如何使其正确显示?
- 我正在尝试编写将 ASCII 转换为十进制、添加并转换回 ASCII 的软件
- C++-将ASCII字符数组中可能的数值转换为字符的最简单方法
- 如何将ASCII数字转换为从文件中提取的整数
- 将非 ASCII 字符转换为英语对应字符C++
- 在Qt中将QString转换为ASCII值,反之亦然
- 输出使用 cout 转换为 ASCII 的文本时输出格式不正确,C++
- 如何在不将其转换为 ASCII 字符的情况下显示 QByteArray 的十六进制值
- 如何使用 ASCII 转换使用字符堆栈计算后缀表达式
- C++将 ASCII 转换为莫尔斯电码
- 找到排列的ASCII转换
- c 中的字符串和int的condanation.从ASCII转换为十六进制
- 如何从ASCII转换为字符串或符号
- 从 ASCII 转换回字符
- 将ascii转换为char
- 我如何从ASCII转换到十六进制值,也增加char指针
- 使用c++将ASCII转换成十六进制的无符号int形式
- 将ASCII转换为Unsigned Int,反之亦然