zoukankan      html  css  js  c++  java
  • word search(二维数组中查找单词(匹配字符串))

    Given a 2D board and a word, find if the word exists in the grid.

    The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

    For example,
    Given board =

    [
      ['A','B','C','E'],
      ['S','F','C','S'],
      ['A','D','E','E']
    ]
    

    word = "ABCCED", -> returns true,
    word = "SEE", -> returns true,
    word = "ABCB", -> returns false.

    从二维数组中找字符串是否存在,而且同一个元素不能重复使用。这是字符串匹配类型 题目,要记住方法。将二维数组简化成字符串,也就是字符串匹配了(依次遍历每个元素,将其当做开头,开始匹配)。

    1、可以想到的是使用回溯法。

    2、不能重复使用,想到用一个数组来标记每个元素的使用情况。

    3、其实就是一个字符一个字符地匹配,当前字符相同,则向四周匹配。

    4、从二维数组哪个字符开始匹配呢?遍历二维数组,依次将字符当做第一个字符跟字符串开始匹配。

    一些注意事项,见代码中的标记。

    class Solution {
        public boolean exist(char[][] board, String word) {
            if(board==null||board.length==0) return false;
            //用一个数组表示某个位置上的元素是否已经使用过
            int m=board.length;
            int n=board[0].length;
            boolean[] flag=new boolean[m*n];
            //从每个位置开始遍历看是否包含此字符串。
            for(int i=0;i<m;i++)
                for(int j=0;j<n;j++){
                    if(helper(board,word,i,j,flag,0)) return true;
                }
            return false;
        }
        public boolean helper(char[][] board,String word,int i,int j,boolean[] flag,int index){
        //当index大于Word的最后一个位置,也就是前面匹配都成功了,可以返回true。
    if(index==word.length()) return true;
    if(i<0||i>=board.length||j<0||j>=board[0].length||board[i][j]!=word.charAt(index)||flag[i*board[0].length+j]) return false; //符合要求后,表示当前字符与字符串中对应字符相等,将该字符标记为使用过,再去判断剩下的字符。 flag[i*board[0].length+j]=true; if(helper(board,word,i+1,j,flag,index+1)||helper(board,word,i-1,j,flag,index+1) ||helper(board,word,i,j-1,flag,index+1)||helper(board,word,i,j+1,flag,index+1)) return true;
          
          
           //这里是关键,如果后面不匹配,就得把该位置的标志清除了,然后返回进行其他位置的比对,不清除会影响结果。
    //如果后面的不匹配,就得把当前的标志清除返回。 flag[i*board[0].length+j]=false; return false; } }
  • 相关阅读:
    kuryr环境搭建
    使用docker搭建kafka环境
    记一次解决curl https证书问题
    一篇精彩的洗地文
    个人知识管理利器wiz
    Markdown写作
    用Bottle开发web程序(二)
    用Bottle开发web程序(一)
    Magnum Kubernetes源码分析(二)
    DVWA(九):File Upload 全等级文件上传
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8228100.html
Copyright © 2011-2022 走看看