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

}

猜你喜欢

转载自blog.csdn.net/weixin_42967016/article/details/85070966