*[Lintcode]Word Search 单词搜索

本文介绍了一个二维网格中查找特定单词的算法实现。采用深度优先搜索(DFS)策略,从每个可能的位置开始递归搜索目标单词,确保不重复使用同一字母。通过具体的代码示例展示了如何在给定的字符矩阵中寻找指定的单词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Example

Given board =

[
  "ABCE",
  "SFCS",
  "ADEE"
]

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

分析:实现题。双重循环+DFS。以board中每一个字符为起点,查看是否可以找到目标字符串。

public class Solution {
    /**
     * @param board: A list of lists of character
     * @param word: A string
     * @return: A boolean
     */
    public boolean exist(char[][] board, String word) {
        if(word == null || word.length() == 0) return true;
        if(board.length == 0 || board[0].length == 0) return false;
        boolean[][] visit = new boolean[board.length][board[0].length];
        
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if(helper(board, visit, i, j, 0, word)) return true;  
            }
        }
        return false;
    }
    
    boolean helper(char[][] board, boolean[][] visit, int row, int col, int index, String str) {
        if(index >= str.length()) {
            return true;
        }
        
        if(row < 0 || col < 0 || row >= board.length || col >= board[0].length) {
            return false;
        }
        
        if(!visit[row][col] && str.charAt(index) == board[row][col]) {
            visit[row][col] = true;//<-
            boolean res = helper(board, visit, row + 1, col, index + 1, str) || 
                helper(board, visit, row - 1, col, index + 1, str) ||
                helper(board, visit, row, col + 1, index + 1, str) ||
                helper(board, visit, row, col - 1, index + 1, str);
            visit[row][col] = false;//<-
            return res;
        }
        
        return false;
    }
}



### LintCode 1369 最频繁单词 解法 LintCode 平台上编号为 1369 的题目涉及统计最频繁出现的单词。以下是对此类问题的一种通用解法。 #### 方法概述 此问题可以通过哈希表来解决,其中键表示不同的单词,而值则记录每个单词出现的次数。通过遍历输入数据并更新哈希表中的计数值,最终找到频率最高的单词及其对应的频次。 #### 实现细节 为了实现这一目标,可以按照以下逻辑编写代码: 1. **预处理**: 清理输入字符串,移除标点符号并将所有字母转换成小写形式以便统一比较标准。 2. **构建词频映射**: 使用 Python 中的 `collections.Counter` 或手动维护一个字典结构存储各单词与其对应出现次数之间的关系。 3. **查找最大值**: 遍历上述得到的词频映射找出具有最高频率的那个单词或者多个相同频率的最大者之一即可满足需求。 下面是基于以上思路的具体实现代码: ```python from collections import Counter import re def topKFrequentWords(words, k): # 正则表达式替换非字母字符为空格,并分割成列表 cleaned_words = re.sub(r'[^a-zA-Z]', ' ', words).lower().split() # 统计词频 count = Counter(cleaned_words) # 获取按频率降序排列的结果 candidates = list(count.items()) candidates.sort(key=lambda w: (-w[1], w[0])) # 返回前K个高频单词 return [word for word, freq in candidates[:k]] # 测试样例 words = "the sky is blue and the color of the sea is also blue" print(topKFrequentWords(words, 2)) # 输出可能为 ['blue', 'the'] ``` 在此段代码中我们利用了正则表达式的功能去除了不必要的特殊字符,并且采用了大小写的标准化操作使得不同格式下的同一词语能够被正确识别为同一个实体。最后借助于Python内置库`Counter`完成了高效地词频计算工作[^1]。 #### 注意事项 - 当存在若干个拥有相同比率的候选答案时,应优先选取字典顺序靠前者作为最终结果的一部分条件。 - 输入验证非常重要,在实际应用环境中应当加入更多异常情况检测机制以增强程序健壮性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值