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;
        }
    }
    
  • 相关阅读:
    uboot 环境变量
    U-boot的环境变量: bootcmd 和bootargs
    linux中的rootfs/initrd/ramfs/initramfs
    关于Linux启动时挂载rootfs的几种方式
    u-boot-2011.06在基于s3c2440开发板的移植之引导内核与加载根文件系统
    MySQL列出当前月的每一天
    SQL 标量函数-----日期函数 day() 、month()、year()
    mysql 中 DATE_ADD函数和 DATE_SUB函数用法
    mysql 中 DATE_ADD(date,INTERVAL expr type)
    mysql中date_add()函数的使用?
  • 原文地址:https://www.cnblogs.com/mapoos/p/14797463.html
Copyright © 2011-2022 走看看