題目地址:
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;
}
}
時間複雜度(爲字符串個數,爲字符串最長長度),空間。