【LeetCode】查找和替换模式Java题解

117 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天,点击查看活动详情

题目描述

你有一个单词列表 words 和一个模式  pattern,你想知道 words 中的哪些单词与模式匹配。

如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后,我们就得到了所需的单词,那么单词与模式是匹配的。

(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。)

返回 words 中与给定模式匹配的单词列表。

你可以按任何顺序返回答案。


示例:

输入:words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
输出:["mee","aqq"]
解释:
"mee" 与模式匹配,因为存在排列 {a -> m, b -> e, ...}。
"ccc" 与模式不匹配,因为 {a -> c, b -> c, ...} 不是排列。
因为 ab 映射到同一个字母。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-and-replace-pattern
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路分析

  • 今天的算法题目是数组处理题目,题目要求判断 words 中哪些单词与模式匹配。我们判断模式是否匹配,就是找 pattern 的规律。
  • 这个问题容易理解,思路很容易就想到了,接下来需要我们把思路转换成代码。两个模式相同,需要两者任一位置的字符都相同,我们定义一个 hashmap 来实现,记录 word 和 pattern 中单词的对应关系。若相等,则是一个答案。实现代码如下,供参考。

通过代码

class Solution {
    public List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> ans = new ArrayList<String>();
        for (String word : words) {
            if (match(word, pattern) && match(pattern, word)) {
                ans.add(word);
            }
        }
        return ans;
    }

    public boolean match(String word, String pattern) {
        Map<Character, Character> map = new HashMap<Character, Character>();
        for (int i = 0; i < word.length(); ++i) {
            char x = word.charAt(i), y = pattern.charAt(i);
            if (!map.containsKey(x)) {
                map.put(x, y);
            } else if (map.get(x) != y) { 
                return false;
            }
        }
        return true;
    }
}

总结

  • 上述算法的时间复杂度是O(nm),空间复杂度是O(n)
  • 坚持算法每日一题,加油!