使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
Getting run-time error while USING SET(C++) to check if two given strings are anagrams
链接到问题: 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);
相关文章:
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 检查字符串是否是拉平德罗姆
- 检查字符串是否是数字,然后将该数字转换为 int?
- 当通过常量和不是字符串的最佳选择时,是否有任何情况?
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 是否可以动态检查文本字符串是否是 C++ 中给定类的成员?
- 检查字母字符串是否是C 中的palindrome
- 如何测试字符串是否是有效的C++(ish)表达式
- C++函数来检查 char 是否是大写字母,并且不计算给定字符串中的大写字母
- 在编译时检查模板参数是否是一种字符串
- 什么是最快检查字符串数组中是否存在字符串的方法
- 检查字符串向量是否是其中一个元素中的子字符串
- C 检测用户是否输入字符串而不是INT
- 是正则是查看字符串是否是另一个弦的好方法
- 检查一个字符串是否是另一个字符串的排列C++
- 如何检查字符串是否是另一个字符串的正确子集
- 有条件地确定字符串是否是数组的一部分
- Strchr不起作用,或者我需要一个替代方案来检查给定字符串中的任何字符是否是另一个字符串的一部分
- 如何使用if语句来检查字符串文字是否是某个单词或短语
- 最有效的检查对象是否是字符串的方法