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

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