1

我是一个初学者,我想知道是否有人可以告诉我这个词搜索我做错了什么?我坚持检查形式参数中指定的单词的每一行,目前它不做任何类型的检查,它的 jst 是一个基本的布尔方法,如果在数组的一行中找到一个单词,则返回 true。假设单词搜索数组是长方形的

    public boolean checkRow( char[][] puzzle, String w)
{
    int counter = 0;
    boolean match = true;
    for ( int row = 0; row < puzzle.length; row++)
    {
        counter = 0;


        for ( int col = 0; col < puzzle[row].length; col++)
        {
            if ( counter <= w.length() )
            {
                char word = puzzle[row][col];


                if( w.charAt(counter) == word)
                {
                    match = true;
                    counter++;
                }
            }


            else if ((counter == w.length()) && (match == true))
            {
                return true;
            }


             else 
            {

                match = false;
                counter = 0;
            }



        }
    }


    return match;
}
4

1 回答 1

2

这是您更正的代码

public boolean checkRow(char[][] puzzle, String w) {
    int counter = 0;
    boolean match = true;
    for (int row = 0; row < puzzle.length; row++) {
        counter = 0;
        match = false;

        for (int col = 0; col < puzzle[row].length; col++) {
            if (counter < w.length()) {
                char word = puzzle[row][col];

                if (w.charAt(counter) == word) {
                    match = true;
                    counter++;
                } else {
                    match = false;
                    counter = 0;
                }

                if ((counter == w.length()) && (match == true)) {
                    return true;
                } 
            }
        }
    }
    return false;
}

但这不是如何进行检查的最佳方法,这里的代码更流畅甚至更快(大约 5 次,我会测试它)

public boolean checkRow2(char[][] puzzle, String w) {
    String rowStr = null;
    for(int row = 0; row < puzzle.length; row++) {
        rowStr = new String(puzzle[row]);
        if(rowStr.contains(w)) return true;
    }
    return false;
}
于 2011-06-14T17:35:14.913 回答