zoukankan      html  css  js  c++  java
  • 0890. Find and Replace Pattern (M)

    Find and Replace Pattern (M)

    题目

    Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.

    A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.

    Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.

    Example 1:

    Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
    Output: ["mee","aqq"]
    Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. 
    "ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.
    

    Example 2:

    Input: words = ["a","b","c"], pattern = "a"
    Output: ["a","b","c"]
    

    Constraints:

    • 1 <= pattern.length <= 20
    • 1 <= words.length <= 50
    • words[i].length == pattern.length
    • pattern and words[i] are lowercase English letters.

    题意

    在一个单词列表中找到所有符合pattern形式的单词。

    思路

    问题可以转化为找到所有的单词,使这个单词中的字符能与pattern中的字符建立起一对一的映射。


    代码实现

    Java

    class Solution {
        public List<String> findAndReplacePattern(String[] words, String pattern) {
            List<String> ans = new ArrayList<>();
    
            for (String word : words) {
                if (judge(word, pattern)) ans.add(word);
            }
            
            return ans;
        }
    
        private boolean judge(String word, String pattern) {
            if (word.length() != pattern.length()) return false;
            
            Map<Character, Character> dict = new HashMap<>();
    
            for (int i = 0; i < word.length(); i++) {
                char c1 = word.charAt(i);
                char c2 = pattern.charAt(i);
                
                if (!dict.containsKey(c1) && dict.containsValue(c2)) {
                    return false;
                } else if (!dict.containsKey(c1)) {
                    dict.put(c1, c2);
                } else if (dict.get(c1) != c2) {
                    return false;
                }
            }
    
            return true;
        }
    }
    
  • 相关阅读:
    HTTP协议详解(真的很经典)
    几点建议,让Redis在你的系统中发挥更大作用
    Redis能干啥?细看11种Web应用场景
    Java中使用Jedis操作Redis
    java的锁机制——synchronized
    web开发中的两把锁之数据库锁:(高并发--乐观锁、悲观锁)
    一分钟教你知道乐观锁和悲观锁的区别
    $^,$@,$?,$<,$(@D),$(@F) of makefile
    linux shared lib 使用与编译
    makefile learning
  • 原文地址:https://www.cnblogs.com/mapoos/p/14797463.html
Copyright © 2011-2022 走看看