LeetCode刷题笔记 890. 查找和替换模式

题目描述

你有一个单词列表 words 和一个模式 pattern,你想知道 words 中的哪些单词与模式匹配。
如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后,我们就得到了所需的单词,那么单词与模式是匹配的。
(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。)
返回 words 中与给定模式匹配的单词列表。
你可以按任何顺序返回答案。

示例:
输入:words = [“abc”,“deq”,“mee”,“aqq”,“dkd”,“ccc”], pattern = “abb”
输出:[“mee”,“aqq”]

总结

双映射的方法和思想
本来想用replace的方法做的,但不知道为什么不起作用

Sample Code

class Solution {
    public List<String> findAndReplacePattern(String[] words, String pattern) {
       List<String> re = new ArrayList<>();
        for (int i = 0; i < words.length; i++) {
            if (isPattern(words[i], pattern) && isPattern(pattern, words[i])) {
                re.add(words[i]);
            }
        }
        return re;
    }

    private boolean isPattern(String word, String pattern) {
        if (word.length() != pattern.length()) return false;
        char[] chs = new char[26];
        for (int i = 0; i < word.length(); i++) {
            int j = word.charAt(i) - 97;
            if (0 == chs[j]) chs[j] = pattern.charAt(i);
            else if (chs[j] != pattern.charAt(i)) {
                return false;
            }
        }
        return true;
    }
}

Demo&Sample Code

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

    public boolean match(String word, String pattern) {
        Map<Character, Character> m1 = new HashMap();
        Map<Character, Character> m2 = new HashMap();

        for (int i = 0; i < word.length(); ++i) {
            char w = word.charAt(i);
            char p = pattern.charAt(i);
            if (!m1.containsKey(w)) m1.put(w, p);
            if (!m2.containsKey(p)) m2.put(p, w);
            if (m1.get(w) != p || m2.get(p) != w)
                return false;
        }

        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值