890. Find and Replace Pattern - LeetCode

Question

890. Find and Replace Pattern

Solution

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

思路:

举例:words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
abb -> 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;
}
posted @ 2018-08-21 23:36  okokabcd  阅读(361)  评论(0编辑  收藏  举报