1

以前の質問のコードを修正したところ、次のようになりました。

//#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <chrono>
#include <cassert>

using namespace std;
const int  MAX_SIZE=10000;
const int MAX_STRINGS = 10;
char** strings=new char*[10];
int len;

char* GetLongestCommonSubstring( char* str1, char* str2 );
inline void readNumberSubstrings();
inline const char* getMaxSubstring();

void readNumberSubstrings()
{
    cin >> len;

    assert(len >= 1 && len <=MAX_STRINGS);

    for(int i=0; i<len;i++)
        strings[i]=new char[MAX_SIZE];

    for(int i=0; i<len; i++)
        cin >> strings[i];
}

 const char* getMaxSubstring()
{
    char *maxSubstring=strings[0];
    auto begin = chrono::high_resolution_clock::now();
    for(int i=1; i < len; i++)
        maxSubstring=GetLongestCommonSubstring(maxSubstring, strings[i]);
    cout << chrono::duration_cast <chrono::milliseconds>       (chrono::high_resolution_clock::now()-begin).count() << endl;
    return maxSubstring;
}

char* GetLongestCommonSubstring( char* string1, char* string2 )
{

    if (strlen(string1)==0 || strlen(string2)==0) cerr << "error!";

    int *x=new int[strlen(string2)+ 1]();
    int *y= new int[strlen(string2)+ 1]();

    int **previous = &x;
    int **current = &y;

    int max_length = 0;
    int result_index = 0;

    int length;
    int M=strlen(string2) - 1;

    for(int i = strlen(string1) - 1; i >= 0; i--)
    {
        for(int j = M; j >= 0; j--) 
        {
            if(string1[i] != string2[j]) 
                (*current)[j] = 0;
            else 
            {
                length = 1 + (*previous)[j + 1];
                if (length > max_length)
                {
                    max_length = length;
                    result_index = i;
                }

                (*current)[j] = length;
            }
        }

        swap(previous, current);
    }
    delete[] x;
    delete[] y;
    string1[max_length+result_index]='\0';
    return &(string1[result_index]);
}

int main()
{
    readNumberSubstrings();
    cout << getMaxSubstring() << endl;
    return 0;
}

一般化された最長共通部分文字列の問題はまだ解決されており、現在はかなり高速です。しかし、落とし穴があります。たとえば、ユーザーが入力しようとしている文字列の数として 3 を指定し、実際に 1 つの文字列だけを入力した場合、このコードは永遠に待機します。どうすればそれを変更できますか?

4

1 に答える 1

0

ファイルから読み取り、引数の数が提供された引数の数と等しくない場合は、適切でクリーンなエラー メッセージをユーザーに表示するだけです。

"Expected 7 arguments, received 3:" 見つかった引数を出力して、ユーザーがエラーを吐き出したときにプログラムが何を見ているのかを理解できるようにします。

人間の意見については、コメントに同意します。ユーザーがプログラムを閉じるか、必要な引数をすべて入力するまで、プログラムは待機する必要があります。

于 2013-09-20T23:34:19.803 に答える