在多维数组中搜索单词,Java

时间:2016-01-26 15:11:58

标签: java arrays string multidimensional-array word

我想在Java中搜索单词拼图中的单词。 如上所述,搜索是水平,垂直和对角线。 我创建了一个数组,但我不知道如何创建一个String,并在我的String中搜索单词。我需要知道如何拥有一个保存表的所有值的String,以及如何键入单词并在此处搜索它。

我知道单词的搜索是使用indexOf函数完成的,但我不知道如何执行它。     import java.util.Scanner;

public class main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int IntegerPosition;
        int IntegerPosition2;
        String position="";
        String word="";
        Scanner s = new Scanner(System.in);
        String content="";
        String[][] sopa = {
                {"X","F","E","K","J","U","I","R","S","H"}, 
                {"Z","H","S","W","E","R","T","G","O","T"},
                {"B","R","A","B","F","B","P","M","V","U"}, 
                {"D","W","E","R","O","O","J","L","L","W"},
                {"U","T","O","N","I","R","O","B","C","R"},
                {"O","P","R","O","V","I","I","K","V","B"},
                {"N","I","Q","U","E","N","T","N","S","A"},
                {"O","V","U","L","R","O","S","S","O","T"},
                {"A","S","A","X","J","T","R","R","I","T"},
                {"R","K","M","E","P","U","B","O","T","A"}
        };
        for (int i = 0; i < sopa[0].length; i++){
            for(int j = 0; j < sopa[i].length; j++){
                content += sopa[i][j];
            }
            System.out.println(content);
            content = "";
        }
        System.out.println("Type the word you are looking for");
        word = s.next();

        for (int i = 0; i < sopa[0].length-1; i++){//t1.length
            for(int j = 0; j < sopa[i].length-1; j++){


            }
        }
        System.out.println(content);
        content = "";
    }

}

1 个答案:

答案 0 :(得分:0)

首先,你应该声明什么&#34;找到一个单词&#34;手段。我想你想在每行和每列中找到字母序列。对角线怎么样?向后?环绕?

我想到了两个解决方案:

  1. 使用String索引:
    • 构建所有字符的字符串。这需要针对每个方向(水平,垂直,对角线)进行,但是如果您反向搜索术语以进行向后搜索,则只能按正向顺序进行。为了有效实施,StringBuilder是您的朋友。
    • 使用String.indexOf查找索引中术语的出现次数。最后,您必须从String位置计算行和列,如果不允许换行,请检查该单词是否跨越任何行/列边界。
    • 如果我不得不寻找许多条款,我会使用它。
  2. 使用数组
    • 也适用于每个方向(水平,垂直,对角线)
    • 查找搜索词在数组中的第一个字母的出现(通过简单迭代)。请注意,当术语不适合行/列时,您可以停止,因此对于6个字母的单词,您可以跳过最后5行/列。
    • 如果您找到了一个锚(即匹配的字母),请检查该单词的后续字母。取消不匹配,否则您已找到出现。
  3. 对于更复杂的匹配实现,可能会感兴趣Boyer-Moore algorithm