2013-10-17 23 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

相關問題