使用C ++检查两个字符串是否为字谜 [英] Check whether two strings are anagrams using C++
问题描述
我想出了下面的程序来检查两个字符串是否是字谜。它适用于较小的字符串,但适用于较大的字符串(我尝试过:听过,应征入伍)它给了我一个不!
The program below I came up with for checking whether two strings are anagrams. Its working fine for small string but for larger strings ( i tried : listened , enlisted ) Its giving me a 'no !'
帮助!
#include<iostream.h>
#include<string.h>
#include<stdio.h>
int main()
{
char str1[100], str2[100];
gets(str1);
gets(str2);
int i,j;
int n1=strlen(str1);
int n2=strlen(str2);
int c=0;
if(n1!=n2)
{
cout<<"\nThey are not anagrams ! ";
return 0;
}
else
{
for(i=0;i<n1;i++)
for(j=0;j<n2;j++)
if(str1[i]==str2[j])
++c;
}
if(c==n1)
cout<<"yes ! anagram !! ";
else
cout<<"no ! ";
system("pause");
return 0;
}
推荐答案
我很懒,所以我将使用标准库功能对两个字符串进行排序,然后进行比较:
I am lazy, so I would use standard library functionality to sort both strings and then compare them:
#include <string>
#include <algorithm>
bool is_anagram(std::string s1, std::string s2)
{
std::sort(s1.begin(), s1.end());
std::sort(s2.begin(), s2.end());
return s1 == s2;
}
一个小的优化可能是检查字符串的大小是否相同在排序之前。
A small optimization could be to check that the sizes of the strings are the same before sorting.
但是,如果该算法被证明是瓶颈,我将暂时摆脱一些惰性并将其与简单的计数解决方案进行比较:
But if this algorithm proved to be a bottle-neck, I would temporarily shed some of my laziness and compare it against a simple counting solution:
- 比较字符串长度
- 实例化计数图,
std :: unordered_map< char,unsigned int> ; m
- 在
s1
上循环,增加每个char的计数
。 - 在
s2
上循环,减少每个char $ c的计数$ c>,然后检查计数是否为
0
- Compare string lengths
- Instantiate a count map,
std::unordered_map<char, unsigned int> m
- Loop over
s1
, incrementing the count for eachchar
. - Loop over
s2
, decrementing the count for eachchar
, then check that the count is0
这篇关于使用C ++检查两个字符串是否为字谜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!