2015-10-14 52 views
1

我的anagram程序在我的dev-cpp中工作得很好,但是在任何在線測試人員都會在任何測試字符串上拋出錯誤的答案。有人能幫我嗎?Anagram程序測試

#include<iostream> 
#include<cstring> 
using namespace std; 

int main() 
{ 

    char input1[10000]; 
    char input2[10000]; 
    cin >> input1; 
    getchar(); 
    cin >> input2; 
    getchar(); 

    int leng; 
    leng = strlen(input1); 
    bool output[leng]; 

    for(int i=0; i<leng; i++){ 
      for(int y=0; y<leng; y++){ 
        if(input1[i] == input2[y]){ 
         output[i] = true; 
        } 
      } 
    } 

    for(int o=0; o<leng; o++){ 
     if((o+1) == leng){ 
      if(output[o] == true){ 
       cout << "ano" << endl; 
       break; 
      } 
     }else if(output[o] == true) { 
       continue; 
     } 
     cout << "nie" << endl; 
     break; 
    } 


    getchar(); 
    return 0; 
} 
+1

你能在你的問題中展示一個適合你的例子,但不能在線嗎? – agold

+0

大概... kalerab mrkvicka ......在PC它拋出我的「不」,但在線「是」,但林不知道有關例子 – Xengo

回答

0

您的算法存在問題。想象一下以下情形:

Input1: ab 
Input2: cdefab 

你的算法將返回OK,因爲它只會檢查輸入1的& B個字符出現在輸入2。

同樣的問題舉例如:

Input1: aaaaaa 
Input2: a 

或者:使用256(指數的數組

  • 計數字符:

    Input1: aaaab 
    Input2: bbbba 
    

    你可以改變你的算法你的ASCII字符)int初始化爲0.遞增input1和遞減input2,最後您的數組應該填充0. O(n)算法

  • 對兩個輸入進行排序並將它們的字符進行比較。 O(n^2)算法

你可以找到更多關於這些算法here的細節。

1

而不是試圖重新發明輪子,有一個整潔的功能is_permutation<algorithm>,可以使這個問題微不足道。 。

#include <algorithm> 

bool isAnagram(std::string a, std::string b) { 
    if(a.size() == b.size()) { 
     return std::is_permutation (a.begin(), a.end(), b.begin(), [](char x, char y){return std::tolower(x) == std::tolower(y);}); 
    } 
    return false; 
} 

只要刪除二元預測,如果你想區分大小寫。 Try it here

+2

你是完全正確的,但我覺得OP是試圖實現他自己的算法,以便學習編程......這只是我的一個想法。 –

+0

是的,我只是學習,但謝謝你們。我知道哪裏犯了錯誤。 – Xengo