0

問題のテキストには次のように書かれています: Find the longest substring in a given stringformed with words that have 2 or more letters in common(the words must be neighbors in the substring(one after the other)) . 制約: 実行時間は O(n^2) 未満でなければなりません。

もう 1 つの制限は、プログラムには 2 つの単語を比較して、2 つ以上の文字が共通しているかどうかを判断するメソッドが必要であるということです。この関数は O(n) 時間で実行する必要があります。

メソッドで O(n) 時間を達成するために私が考えた唯一の方法は、ハッシュテーブルを使用することです(これを達成しようとするメソッドの名前は「検索」です)。これは私の問題の実装です:

public class Subiectul1 {
    String str1;

    Subiectul1(String str1){
        this.str1 = str1;
    }

    public boolean find(String str1, String str2){
        Hashtable<String,Integer> hash = new Hashtable<String,Integer>();
        int count = 0;

        str1 = str1.toLowerCase();
        str2 = str2.toLowerCase();

        for(int i = 0; i < str1.length(); i++){
            hash.put(String.valueOf(str1.charAt(i)), 1);
        }

        for(int i = 0; i < str2.length(); i++){
            if(hash.containsKey(String.valueOf(str2.charAt(i)))) {
                count++; 
                hash.remove(String.valueOf(str2.charAt(i)));
            }
        }

        if(count >= 2) return true;

        return false;
    }

    public void solve(){
        String[] a_str1 = str1.split(" ");
        int n = a_str1.length;
        int[] lmax = new int[n];
        int[] succ = new int[n];
        int max = 0;
        int pmax = -1;

        lmax[n - 1] = 1;
        succ[n - 1] = -1;

        for(int i = n - 2; i >= 0; i--){
            max = 0;
            pmax = -1;
            for(int j = i + 1; j < n; j++)
                if(find(a_str1[i],a_str1[j]) && (max < lmax[j])){
                    max = lmax[j];
                    pmax = j;
                }

            lmax[i] = max + 1;
            succ[i] = pmax;
        }

        pmax = 0;
        max = lmax[0];

        for(int i = 1; i < n; i++)
            if(lmax[i] > max ) {
                pmax = i;
                max = lmax[pmax];
            }

        int i = pmax;
        while(i != -1){
            System.out.print(a_str1[i] + " ");
            i = succ[i];
        }

    }
}

これは私が考えることができる最高のものなので、他の誰かがより良いアイデアを持っているかどうか知りたい.

4

0 に答える 0