检查两个字符串是否彼此置换
Check if two strings are permutation of each other
我正在解决一个难题,该难题需要检查两个字符串是否在O(n(中使用O(1(空间彼此置换。
所以我的想法是将两个字符串加成,如果结果为零,则是置换。
,但仅在一个测试用例中失败
Input1: pro
Input2: pro
Pass
Input1: firecode
Input2: firecoat
Pass
Input1: firecode
Input2: codefire
Pass
Input1: abcd
Input2: cadb
Pass
Input1: GOD
Input2: DOG
Pass
Input1: [Empty]
Input2: [Empty]
Pass
Input1: firecode
Input2: firec
Pass
Input1: bbbb
Input2: dddd
Fail
这是我的实现:
bool permutation(string input1, string input2)
{
string conct = input1+input2;
int result = 0;
for (int i =0; i < conct.size(); i++)
{
result^=conct[i];
}
return result ==0;
}
具有O(1(额外空间的经典O(n(解决方案,对于可能的数据,很少有值是构建出现表并计算每个元素的次数多少次发生。对于字符串,这很容易:
bool permutation(string input1, string input2) {
int count[UCHAR_MAX+1] = {};
for(unsigned char c: input1) count[c]++;
for(unsigned char c: input2) count[c]--;
for(int x: count) {
if(x) return false;
}
return true;
}
请注意,我在unsigned char
中读取了每个字符,因为已定义了Plain char
的签名,并且您实际上并不想用负值索引我的数组。
只需使用std :: is_permunt。
bool permutation(const string &input1, const string &input2)
{
return std::is_permutation(
input1.begin(), input1.end(),
input2.begin(), input2.end());
}
我认为您的解决方案方法有逻辑错误。
您要检查的是两个字符串中是否有相同的字母,这些字母的发生数量相同。
在您的方法中,您正在检查的是,如果限入的字符串为每个字母都有偶数。
如果输入"地狱"answers" helloo",您会发现您的方法在0中会导致0,即使这些字符串不是另一个字符串的排列。
查看ASCII二进制表您还可以构造诸如" AB"answers" C@"之类的东西,结果为0:
A 0100 0001
B 0100 0010 ^= 0000 0011
C 0100 0011 ^= 0100 0000
@ 0100 0000 ^= 0000 0000
result 0000 0000
编辑:更正的说明,添加了另一个示例
您可以在此处使用地图数据结构,并在两个字符串中找到每个元素的频率。如果对于任何角色的频率都不同,则意味着错误。
相关文章:
- 是否可以在c++中处理字符串流中的各个元素
- 是否可以从格式字符串中检索"width"
- C++-字符串是否包含一个带有简单循环的单词
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 是否可以将带有字符串化运算符的宏转换为 constexpr?
- 检查字符串是否"null" C++
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 是否有通用方法可以找到任何以 null 结尾的字符串的长度?
- 检查字符串是否为整数
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- 返回从字符串文本创建的静态string_view是否安全?
- 如何检查模板类中的变量是否为字符串类型?
- 是否保证相同内容字符串文本的存储相同?
- 检查数组中是否有字符串中的值,如果没有,则添加它
- 在这种情况下,使用 string_view 是否会导致不必要的字符串复制?
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 是否可以创建一个用户定义的文本,将字符串文本转换为 own 类型的数组?
- 如何检查字符串中是否有重复的负号?例如 --1
- 如何检查字符串是否正确以将其转换为 int?