1. 程式人生 > >【leetcode】查詢和替換模式

【leetcode】查詢和替換模式

題目要求

如果有一個單詞列表words,和一個模式pattern

  • 如果存在字母的排列p,使得將模式中的每個字母x替換為p(x)之後,
  • 我們就得到了所需單詞,那麼單詞與模式是匹配的。返回words中與給定模式匹配的單詞列表。
  • 示例:
  • 輸入:words=[“abc”,“deq”,“mee”,“aqq”,“dkd”,“ccc”],pattern = “abb”
  • 輸出:[“mee”,“aqq”]

核心思想

利用HashMap,將pattern的字元用作key,將兩個單詞中的元素一一對應,進行匹配。

完整程式碼如下

import java.
util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 查詢和替換模式 * 如果有一個單詞列表words,和一個模式pattern * 如果存在字母的排列p,使得將模式中的每個字母x替換為p(x)之後, * 我們就得到了所需單詞,那麼單詞與模式是匹配的。返回words中與給定模式匹配的單詞列表。 * 示例: * 輸入:words=["abc","deq","mee","aqq","dkd","ccc"],pattern = "abb" * 輸出:["mee","aqq"] * */
public class Solution { public static List<String> findAndReplacePattern(String[] words, String pattern) { List<String> list = new ArrayList<>(); for(int i = 0; i < words.length; i++) { //先判斷長度,第一步篩選 if(words[i].length() != pattern.length()) { continue; } Map<
Character,Character> hashmap = new HashMap<>(); boolean is = true; for(int j = 0; j < words[j].length(); j++) { if(!hashmap.containsKey(pattern.charAt(j))) { //這裡還要判斷一下words,因為j在兩個單詞中的變化是同步的,兩個單詞必須都符合未出現過的條件,以免遺漏了違規單詞 if(!hashmap.containsValue(words[i].charAt(j))) { hashmap.put(pattern.charAt(j),words[i].charAt(j)); } else { is = false; break; } } else { if(hashmap.get(pattern.charAt(j)) != words[i].charAt(j)) { is = false; break; } } } if(is == true) { list.add(words[i]); } } return list; } public static void main(String[] args) { String[] words = {"abc","deq","mee","aqq","dkd","ccc"}; String pattern = "abb"; System.out.println(Solution.findAndReplacePattern(words, pattern)); } }