检查两个字符串是否彼此置换

Check if two strings are permutation of each other

本文关键字:是否 字符串 两个 检查      更新时间:2023-10-16

我正在解决一个难题,该难题需要检查两个字符串是否在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

编辑:更正的说明,添加了另一个示例

您可以在此处使用地图数据结构,并在两个字符串中找到每个元素的频率。如果对于任何角色的频率都不同,则意味着错误。