使用ASCII值确定A是否是B的置换 [英] Determine if A is permutation of B using ASCII values
本文介绍了使用ASCII值确定A是否是B的置换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个函数来确定字符串a
是否是字符串b
的排列.定义如下:
I wrote an function to determine if string a
is a permutation of string b
. The definition is as follows:
bool isPermutation(std::string a, std::string b){
if(a.length() != b.length())
return false;
int a_sum, b_sum;
a_sum = b_sum = 0;
for(int i = 0; i < a.length(); ++i){
a_sum += a.at(i);
b_sum += b.at(i);
}
return a_sum == b_sum;
}
我的方法的问题在于,如果a = 600000
和b = 111111
,则该函数返回true.
The issue with my approach is that if a = 600000
and b = 111111
, the function returns true.
有什么办法可以保持我对这个问题的一般方法(而不是对字符串进行排序然后再进行strcmp
)并保持正确性?
Is there any way I can keep my general approach to this problem (as opposed to sorting the strings then doing strcmp
) and maintain correctness?
推荐答案
您可以分别计算字符:
bool isPermutation(std::string a, std::string b)
{
if(a.length() != b.length())
return false;
assert(a.length() <= INT_MAX);
assert(b.length() <= INT_MAX);
int counts[256] = {};
for (unsigned char ch : a)
++counts[ch];
for (unsigned char ch : b)
--counts[ch];
for (int count : counts)
if (count)
return false;
return true;
}
这篇关于使用ASCII值确定A是否是B的置换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文