890. Find and Replace Pattern

https://leetcode.com/problems/find-and-replace-pattern/

題目

You have a list of words and a pattern, and you want to know which words in words matches the pattern.

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.)

Return a list of the words in words that match the given pattern.

You may return the answer in any order.

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.

Note:

  • 1 <= words.length <= 50
  • 1 <= pattern.length = words[i].length <= 20

解答

我想到的方法是標準化,將一個字符串標準化爲一個相同的東西,比如abb,就標準化爲a1b2,標準化的方法只用從a開始的字符串,如果後面的不同,就用b,如果有相同的,就還用原來的那個。所以需要一個map,去記錄,輸入字符串的字符 -> 編碼字符

class P890_Find_and_Replace_Pattern {
    
    public List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> ret = new ArrayList<>();
        String standard = standard(pattern);

        for (String w : words) {
            if (standard(w).equals(standard)) {
                ret.add(w);
            }
        }

        return ret;
    }

    public static String standard(String pattern) {
        Map<Character, Character> maps = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        char availableC = 'a';
        int c = 0;
        for (int i = 0; i < pattern.toCharArray().length; i++) {
            if (i == 0) {
                c = 1;
                maps.put(pattern.charAt(i), availableC);
                sb.append(availableC);
            } else {
                if (pattern.charAt(i) == pattern.charAt(i - 1)) {
                    c++;
                } else {
                    sb.append(c);
                    if (maps.containsKey(pattern.charAt(i))) {
                        sb.append(maps.get(pattern.charAt(i)));
                    } else {
                        availableC++;
                        maps.put(pattern.charAt(i), availableC);
                        sb.append(availableC);
                    }
                    c = 1;
                }
            }
        }

        sb.append(c);

        return sb.toString();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章