题目地址:
https://leetcode.com/problems/find-and-replace-pattern/
给定一个字符串数组,再给定一个字符串,返回数组中与“模式一样”的字符串。“模式一样”意思是存在一个字母间的双射可以将其中一个字符串变为另一个。
参考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;
}
}
时间复杂度(为字符串个数,为字符串最长长度),空间。