|
| 1 | +## LeetCode890 |
| 2 | +> language:Java |
| 3 | +
|
| 4 | +> version:jdk1.7 |
| 5 | +
|
| 6 | +```java |
| 7 | +/** |
| 8 | + * 思路一:把pattern弄成一个记忆,然后依次比较 |
| 9 | + * 思路二:把pattern的某个特点记录下来,依次比较,然后再把下一个特点记录下来,依次比较... |
| 10 | + * 下面代码是思路一的实现 |
| 11 | + */ |
| 12 | + public static List<String> findAndReplacePattern(String[] words, String pattern) { |
| 13 | + |
| 14 | + List<String> resultList = new ArrayList<>(); |
| 15 | + List<List<Integer>> patternRule = getRule(pattern); |
| 16 | + |
| 17 | + for (int i=0;i<words.length;i++){ |
| 18 | + boolean tempStatus = true; |
| 19 | + //长度不一致,直接下一个 |
| 20 | + if (words[i].length()!=pattern.length()) continue; |
| 21 | + |
| 22 | + List<List<Integer>> wordRule = getRule(words[i]); |
| 23 | + if (patternRule.size()!=wordRule.size()) continue; |
| 24 | + for (int j=0;j<patternRule.size()&&tempStatus;j++){ |
| 25 | + List<Integer> patternRuleIntegers = patternRule.get(j); |
| 26 | + List<Integer> wordRuleIntegers = wordRule.get(j); |
| 27 | + for (int m=0;m<patternRuleIntegers.size();m++){ |
| 28 | + if (patternRuleIntegers.size()!=wordRuleIntegers.size()){ |
| 29 | + tempStatus =false; |
| 30 | + break; |
| 31 | + } |
| 32 | + if (patternRuleIntegers.get(m)!=wordRuleIntegers.get(m)){ |
| 33 | + tempStatus =false; |
| 34 | + break; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + } |
| 39 | + if (tempStatus) resultList.add(words[i]); |
| 40 | + |
| 41 | + } |
| 42 | + return resultList; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * 传入字符串可以获得其规则(aabacc的规则为{{0,1,3},{2},{4,5}}) |
| 47 | + * @param pattern |
| 48 | + * @return |
| 49 | + */ |
| 50 | + public static List<List<Integer>> getRule(String pattern){ |
| 51 | + //记录pattern的所有特点 |
| 52 | + List<List<Integer>> characterList = new ArrayList<>(); |
| 53 | + String currentCharacter = ""; |
| 54 | + List<Integer> recordList = new ArrayList<>(); |
| 55 | + |
| 56 | + for (int i=0;i<pattern.length();i++){ |
| 57 | + if (recordList.contains(i)){ |
| 58 | + continue; |
| 59 | + } |
| 60 | + int tempIndex; |
| 61 | + currentCharacter = pattern.substring(i,i+1); |
| 62 | + List<Integer> tempList=new ArrayList<>(); |
| 63 | + for (int j=i-1;;) { |
| 64 | + tempIndex = pattern.indexOf(currentCharacter, j); |
| 65 | + if (tempIndex==-1) break; |
| 66 | + |
| 67 | + recordList.add(tempIndex); |
| 68 | + tempList.add(tempIndex); |
| 69 | + if (tempIndex==pattern.length()-1) break; |
| 70 | + j=tempIndex+1; |
| 71 | + } |
| 72 | + characterList.add(tempList); |
| 73 | + } |
| 74 | + return characterList; |
| 75 | + } |
| 76 | + |
| 77 | + public static void main(String[] args) { |
| 78 | + String[] words = new String[]{"abc","deq","meemccccm","aqqa","dkd","ccc"}; |
| 79 | + List<String> list = findAndReplacePattern(words, "abbacccca"); |
| 80 | + for (String s : list){ |
| 81 | + System.out.println(s); |
| 82 | + } |
| 83 | + } |
| 84 | +``` |
0 commit comments