2013-10-17 21 views
2

基本上我有一个问题,有2个子问题。 第一个问题是:给定2个字符串,确定它们是否是anagrams。 其次是有点困难。你有N个字符串,并且必须确定它们是否是对方的字典。查找N个字符串是否为对方的字典

我解决了第一个问题,我会写下面的代码,但对于第二个问题我不知道。我认为可以通过从字符串数组中读取N个字符串来做到这一点,然后使用序列来读取每个字符串并对其进行比较,但我不知道如何完成。

#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

如果'string1'是一个字谜'string2'和'string3','string2'和'string3'绝对是彼此的昵称 – Kunal

+0

哦,是的。对不起。我迷失在所有的东西里。即使是这样。我无法弄清楚如何读取字符串数组。我搜索的所有东西都使用了指针,但我还没有学习。 –

+0

@DragoşPaulMarinescu排序字符串检查是非常低效的,没有必要检查我的答案 – aaronman

回答

0

查找两个字符串是否为字符特别容易,特别是对于ASCII字符集。最好的方法是创建一个大小为256的int数组。遍历第一个字符串,并为每个char ++表示int。对第二个字符串做同样的事情,并检查数组是否结束了。

要延长这多个字符串是容易的,因为如果

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

如果您正在使用非ASCII字符集是这样大它可能是使用HashMap,而不是一个bitset的一个好主意。

+0

今天晚些时候我会尝试你的解决方案。首先我想解决它,如果可能的话,根据我已经编写的第一个解决方案。将您的解决方案作为“挑战”很好。 –

+0

@DragoşPaulMarinescu国际海事组织这很简单,如果你真的写自己的排序你的解决方案实际上需要更多的努力,我不想只给你的代码,但我做了约10行代码,所以它不那么难 – aaronman

0

如果X是Y和Z,则Y和Z的字谜也字谜

所以,简单地重复你的逻辑,最简单的方法: -

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 !"; 
+0

当我写std :: vector 的话;编译器给出了一个错误,说“命名空间标准没有成员”矢量“”我以前没有真正使用矢量,所以这对我来说是一个全新的世界。对不起,作为noob :( –

+0

@DragoşPaulMarinescu你需要包括正确的标题请参见[这里](http://ideone.com/JauP1R) – P0W

+0

Woops,忘了#include

相关问题