0

与えられた単語のセットからアナグラムを選別するアルゴリズムを書くことになっています。これまでのところ、私はこれを手に入れました

package Tutorial5;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader; 


public class Anagrams {

    /**
     * @param args
     */
    public static void main(String[] args) {

        try{
            FileInputStream fis = new FileInputStream("src/Tutorial5/words"); //locate and open the txt.file

            DataInputStream dis = new DataInputStream(fis); //get the words from the txt.file

            BufferedReader br = new BufferedReader(new InputStreamReader(dis));

            String SLine;


            while ((SLine = br.readLine()) != null) //read the txt.file line by line
            {
                System.out.println(SLine); //print out the words
        }

        dis.close(); //close the DataInputStream

    }
        catch (Exception e) //see if there is any exception to catch
        {
            System.err.println("Error: " + e.getMessage());
        }

}
}

誰でも私を助けてもらえますか?仕分けの部分で悩んでいます。取得したこのコードを使用して文字列に変換し、アナグラムにソートする方法がわかりません。

4

3 に答える 3

0
Vector<String> strings = new Vector<String>();
while ((SLine = br.readLine()) != null) //read the txt.file line by line
{
    strings.add(SLine);
    System.out.println(SLine); //print out the words
}

これで、それらを並べ替えるために使用できるベクトル内の文字列ができました。ソートアルゴリズムを別の関数として作成します。

void sortStrings(Vector<String> strings) {
// ...
}

あなたが自分自身を見つけることができる実際のソートを行う方法、利用可能なものがたくさんあります:ベクトルをソートするためにどの関数を使用できますか?

于 2012-04-05T11:56:00.283 に答える
0

2 つの単語がアナグラムであるかどうかを調べることは、次のように考えればそれほど複雑ではありません。両方の文字列の長さが同じで文字が同じである限り、それらはアナグラムです。

したがって、2 つの文字列を受け取り、これらの文字列を並べ替えて、同じインデックスに同じ値があるかどうかを確認するメソッドを作成する必要があります。コードでは、これに似たものになります。

  public boolean isAnagram(String str1, String str2) {
     if (str1.length() != str2.length()) 
         return false; // can't be an anagram since not equal length
     for (int i = i<str1.length;i++) { // loop thru the string
        if (str1.charAt(i) != str2.charAt(i)) // is the char at index i in str1 not equal to char at the same index in str2?
            return false;
         }
      return true;

このメソッドが機能するには、文字列を並べ替える必要があり、スペースなどを含めないでください。これは宿題なので、その作業はあなたに任せます:)

于 2012-04-05T12:10:51.293 に答える
0

配列リストをソートするよりも、これらすべての文字列を配列リストにするのはどうですか。印刷中に配列リストに追加して並べ替えます..簡単なコーディング..

于 2012-04-05T16:17:19.750 に答える