【Leetcode】890. Find and Replace Pattern

題目地址:

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

給定一個字符串數組,再給定一個字符串pp,返回數組中與pp“模式一樣”的字符串。“模式一樣”意思是存在一個字母間的雙射可以將其中一個字符串變爲另一個。

參考https://blog.csdn.net/qq_46105170/article/details/105886086。代碼如下:

import java.util.*;

public class Solution {
    public List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> res = new ArrayList<>();
        if (words == null || words.length == 0) {
            return res;
        }
    
        for (String word : words) {
            if (match(word, pattern)) {
                res.add(word);
            }
        }
        
        return res;
    }
    
    private boolean match(String s, String p) {
        if (s.length() != p.length()) {
            return false;
        }
        
        Map<Character, Integer> map1 = new HashMap<>(), map2 = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (!Objects.equals(map1.put(s.charAt(i), i), map2.put(p.charAt(i), i))) {
                return false;
            }
        }
        
        return true;
    }
}

時間複雜度O(nl)O(nl)nn爲字符串個數,ll爲字符串最長長度),空間O(l)O(l)

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