夏天吃辣椒

导航

 

1、双unordered_map(0ms,100%;6.3MB,50%)C++

 1 bool wordPattern(string pattern, string str) {
 2         unordered_map<char,string>str1;
 3         unordered_map<string,char>ch2;
 4 
 5         int length=str.size();
 6         int i=0;
 7         for(char ch:pattern){
 8             //防止substr处越界
 9             if(i>=length)
10             return false;
11             int j=i;
12             while(j<length&&str[j]!=' ') j++;
13             string s=str.substr(i,j-i);
14             
15             //char相同判断string是否不同
16             if(str1.count(ch)&&str1[ch]!=s)
17             return false;
18             //string相同判断char是否不同
19             if(ch2.count(s)&&ch2[s]!=ch)
20             return false;
21 
22             str1[ch]=s;
23             ch2[s]=ch;
24             i=j+1;
25         }
26         return i>length;
27         
28     }

2、HashSet(0ms,100%;36MB,92%)Java

 1   /**
 2      * 记忆数组用于去重、比对pattern。数组下标即为当前pattern
 3      * 数组对应值为之前已有pattern的index,若为-1,则说明之前无相同pattern。
 4      * HashSet用于记忆pattern对应的str是否唯一。规避多个pattern对应相同str的情况
 5      * */
 6     public boolean wordPattern(String pattern, String s) {
 7         String[] strs = s.split(" ");
 8         if(strs.length != pattern.length()){
 9             return false;
10         }
11         int[] memory = new int[26];
12         Arrays.fill(memory, -1);
13         HashSet<String> dict = new HashSet<>();
14         for (int i = 0; i < strs.length; i++) {
15             int flag = pattern.charAt(i) - 'a';
16             if(memory[flag] == -1){
17                 if(dict.contains(strs[i])){
18                     return false;
19                 }
20                 memory[flag] = i;
21                 dict.add(strs[i]);
22             }else {
23                 if(!strs[memory[flag]].equals(strs[i])){
24                     return false;
25                 }
26             }
27         }
28         return true;
29     }

 

posted on 2021-10-03 09:01  夏天吃辣椒  阅读(34)  评论(0)    收藏  举报