890. Find and Replace Pattern - LeetCode

Posted okokabcd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了890. Find and Replace Pattern - LeetCode相关的知识,希望对你有一定的参考价值。

Question

890. Find and Replace Pattern

技术分享图片

Solution

题目大意:从字符串数组中找到类型匹配的如xyy,xxx

思路:

举例:words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
abc -> 011

abc -> 012
deq -> 012
mee -> 011  匹配
aqq -> 011  匹配
dkd -> 010
ccc -> 000

Java实现:

public List<String> findAndReplacePattern(String[] words, String pattern) {
    int[] patternPos = getStrPos(pattern);
    List<String> retList = new ArrayList<>();
    for (String word : words) {
        if (Arrays.equals(getStrPos(word), patternPos)) retList.add(word);
    }
    return retList;
}

private int[] getStrPos(String str) {
    Map<Character, Integer> posMap = new HashMap<>();
    char[] arr = str.toCharArray();
    int[] posArr = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
        if (posMap.get(arr[i]) == null) {
            posMap.put(arr[i], i);
        }
        posArr[i] = posMap.get(arr[i]);
    }
    return posArr;
}

以上是关于890. Find and Replace Pattern - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

LC 890. Find and Replace Pattern

[LeetCode] 890. Find and Replace Pattern

890. Find and Replace Pattern - LeetCode

[LeetCode] 890. Find and Replace Pattern 查找和替换模式

LeetCode 205. Isomorphic Strings; 290. Word Pattern; 890. Find and Replace Pattern

890. 查找和替换模式