Find if N strings are anagrams of each other

a 夏天 提交于 2019-12-11 03:38:42

问题


Basically I have a problem with 2 subquestions. First question is: Given 2 strings, determine if they are anagrams. Second is a bit harder. You have N strings and have to determine if those are anagrams of each other.

I've solved the first one and I'll write the code below, but for the second one I have no idea. I was thinking it's possible to somehow do it by reading N strings from an array of strings, and then to use a for sequence to read each of them and compare them but I have no idea how to exactly.

#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    string word1; string word2;

    getline(cin,word1);
    getline(cin,word2);

    if(word1.length()==word2.length()){
        sort(word1.begin(), word1.end());
        sort(word2.begin(), word2.end());
    if(word1==word2) cout<<"The words are anagrams of each other"<<endl;
    else cout<<"The words are not anagrams of each other"<<endl;
    }
    else cout<<"The words are not the same length"<<endl;
return 0;
}

回答1:


Finding if two strings are anagrams is extremely simple especially for the ASCII character set. The best approach is to create an int array of size 256. Go through the first string and for each char ++ that int. Do the same thing for the second string and check if the array's ended up the same.

To extend this to multiple string is easy since if

a is anagram of b and b is anagram of c then a is anagram of c

If you are doing this with a non ASCII character set that is larger it might be a good idea to use a hashmap instead of a bitset.




回答2:


If X is anagram of Y and Z , then Y and Z are also anagrams

So, simply repeat your logic , the simplest approach :-

std::vector<std::string> words; //Use a vector
size_t i;
std::string word1,word2;
//Get words from standard input
std::copy(std::istream_iterator<std::string> (std::cin),
          std::istream_iterator<std::string>(),
          std::back_inserter(words));

word1=words[0]; //Check anagram with first word
sort(word1.begin(), word1.end());
for(i=1; i<words.size();i++)
{
    word2=words[i];
    sort(word2.begin(), word2.end());
    if(word2!=word1)
       break;
}

if(i==words.size())
    std::cout<<"All Anagrams !";


来源:https://stackoverflow.com/questions/19433464/find-if-n-strings-are-anagrams-of-each-other

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!