检查两个字符串是否是anagrams c ++ [英] Check whether two strings are anagrams c++

查看:363
本文介绍了检查两个字符串是否是anagrams c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;

}

我想出了检查两个字符串是否是anagrams。它的工作罚款小字符串,但对于较大的字符串(我试图:听,登记)它给我一个'不!'帮助!

The above is the program 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 !'help !

推荐答案

我很懒,所以我会使用标准库函数来排序这两个字符串,然后比较它们:

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:


  1. 比较字符串长度

  2. 实例化计数映射, std :: unordered_map< char,unsigned int> ; m

  3. 循环 s1 ,增加每个 code>。

  4. 循环 s2 ,减少每个 char ,然后检查计数 0

  1. Compare string lengths
  2. Instantiate a count map, std::unordered_map<char, unsigned int> m
  3. Loop over s1, incrementing the count for each char.
  4. Loop over s2, decrementing the count for each char, then check that the count is 0

这篇关于检查两个字符串是否是anagrams c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆