|
| 1 | +```java |
| 2 | +package sy181203; |
| 3 | + |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +/** |
| 8 | + * @author suyuan |
| 9 | + * |
| 10 | +你有一个单词列表 words 和一个模式 pattern,你想知道 words 中的哪些单词与模式匹配。 |
| 11 | +
|
| 12 | +如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后, |
| 13 | +我们就得到了所需的单词,那么单词与模式是匹配的。 |
| 14 | +
|
| 15 | +(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。) |
| 16 | +
|
| 17 | +返回 words 中与给定模式匹配的单词列表。 |
| 18 | +
|
| 19 | +你可以按任何顺序返回答案。 |
| 20 | +
|
| 21 | + |
| 22 | +
|
| 23 | +示例: |
| 24 | +
|
| 25 | +输入:words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" |
| 26 | +输出:["mee","aqq"] |
| 27 | +解释: |
| 28 | +"mee" 与模式匹配,因为存在排列 {a -> m, b -> e, ...}。 |
| 29 | +"ccc" 与模式不匹配,因为 {a -> c, b -> c, ...} 不是排列。 |
| 30 | +因为 a 和 b 映射到同一个字母。 |
| 31 | + |
| 32 | +
|
| 33 | +提示: |
| 34 | +
|
| 35 | +1 <= words.length <= 50 |
| 36 | +1 <= pattern.length = words[i].length <= 20 |
| 37 | +
|
| 38 | + */ |
| 39 | +public class leetcode_890查找和替换模式 |
| 40 | +{ |
| 41 | + |
| 42 | + public static void main(String[] args) |
| 43 | + { |
| 44 | + String[] wordsStrings= {"ddd","abc","deq","mee","aqq","dkd","ccc"}; |
| 45 | + String pattern = "abb"; |
| 46 | + System.out.println(findAndReplacePattern(wordsStrings, pattern)); |
| 47 | + |
| 48 | + } |
| 49 | + |
| 50 | + public static List<String> findAndReplacePattern(String[] words, String pattern) |
| 51 | + { |
| 52 | + List<String> list=new ArrayList<String>(); |
| 53 | + for(int i=0;i<words.length;i++) |
| 54 | + { |
| 55 | + if(words[i].length()==pattern.length()) |
| 56 | + { |
| 57 | + if(isMatch(words[i], pattern)) |
| 58 | + list.add(words[i]); |
| 59 | + } |
| 60 | + } |
| 61 | + return list; |
| 62 | + } |
| 63 | + |
| 64 | + public static boolean isMatch(String word,String pattern) |
| 65 | + { |
| 66 | + //不用map,弄个布隆过滤器,双射 |
| 67 | + //直接映射char对应的int值,就不用存数值了 |
| 68 | + int [] map=new int[128]; |
| 69 | + int [] isUse=new int[128]; |
| 70 | + for(int i=0;i<word.length();i++) |
| 71 | + { |
| 72 | + int p=pattern.charAt(i); |
| 73 | + int w=word.charAt(i); |
| 74 | + if(map[p]==0 && isUse[w]==0)//没有匹配过 |
| 75 | + { |
| 76 | + map[p]=w; |
| 77 | + isUse[w]=1; |
| 78 | + } |
| 79 | + else if (map[p]!=w) { |
| 80 | + return false; |
| 81 | + } |
| 82 | + } |
| 83 | + return true; |
| 84 | + } |
| 85 | + |
| 86 | +} |
| 87 | +``` |
0 commit comments