使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误

Getting run-time error while USING SET(C++) to check if two given strings are anagrams

本文关键字:是否是 字符串 运行时错误 检查 C++ SET 使用 两个      更新时间:2023-10-16

链接到问题: https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/two-strings-4/

这些天我从设置和地图开始了。 两个字符串 str1 和 str2 的长度相等。 我必须告诉它们是否是彼此的字谜。 我使用unordered_map通过保持字符数来解决问题,这在线性时间内有效并且很棒。 但是我想使用unordered_multiset但是我遇到了运行时错误。

法典:

#include<bits/stdc++.h>
using namespace std;
int main(){ 
int t;// number of testcases
cin>>t;
while(t--){
string str1,str2;// two strings of equal length str1 and str2
cin>>str1>>str2;
unordered_multiset<char> s1,s2;// two sets 
for(int i=0;i<str1.length();i++){
s1.insert(str1[i]);// initialization
s2.insert(str2[i]);
}
unordered_multiset<char>::iterator itr;
for(itr=s1.begin();itr!=s1.end();itr++){
if(s2.find(*itr)!=s2.end()) s2.erase(itr);/*  if *itr is present in s2 then delete its address .....
i know i am making mistake somewhere here but i can't figure out*/
else {
cout<<"NO"<<"n";// print NO if not found
break;
}
}
if(itr==s1.end()) cout<<"YES"<<"n";// if itr reached the end print YES
}
}

这个想法是遍历集合 s1 并在集合 s2 中找到相应的元素。如果未找到,请打印 NO 并中断,否则从 s2 中删除相应的元素,并且由于我正在使用迭代器删除元素,因此如果一个字符多次出现,则应删除第一次出现。

如果您没有收到我的问题,请告诉我

尝试以更简单的方式解决它。问题指出只有小写字符,您可以为每个单词只使用一个频率数组,然后进行比较。

#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
vector<int> f1(26, 0);
vector<int> f2(26, 0);
string s1, s2;
cin >> s1 >> s2;
for(const char& c : s1) f1[c - 'a']++;
for(const char& c : s2) f2[c - 'a']++;
cout << ( (f1 == f2)? "YES" : "NO") << endl;
}
}

这是因为您使用 s1 中的迭代器从 s2 中删除元素:

if(s2.find(*itr)!=s2.end()) s2.erase(itr);

它必须是这样的:

if(s2.find(*itr)!=s2.end()) s2.erase(*itr);

或:

auto elem = s2.find(*itr);
if (elem != s2.end())
s2.erase(elem);