【问题标题】:Sorting Anagrams排序字谜
【发布时间】:2012-04-05 11:48:37
【问题描述】:

我应该编写一个算法,从给定的单词集中整理出字谜。到目前为止,我得到了这个

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());
        }

}
}

谁能帮帮我?我在分类部分苦苦挣扎。我不知道如何使用我得到的这段代码并将其转换为字符串并将其排序为字谜。

【问题讨论】:

  • 您的输入究竟包含什么?每行只有一个单词,或者已经有一些你只需要排序的字谜。还是您必须从输入的单词中构建字谜?您必须更加精确才能获得建设性的答案。

标签: java


【解决方案1】:
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) {
// ...
}

具体的排序方法你自己找,有很多东西可以用:What function can be used to sort a Vector?

【讨论】:

    【解决方案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;
    

    请注意,要使此方法起作用,字符串需要排序并且不应包含空格等。由于这是家庭作业,我将把这项工作留给你做:)

    【讨论】:

      【解决方案3】:

      如何将所有这些字符串放入数组列表而不是对数组列表进行排序。 在打印时添加到数组列表然后对其进行排序..简单编码..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-22
        • 2019-11-13
        • 1970-01-01
        • 2021-12-30
        • 2020-05-11
        • 2015-11-07
        • 2016-01-12
        相关资源
        最近更新 更多