-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathword pattern.java
More file actions
46 lines (41 loc) · 1.29 KB
/
Copy pathword pattern.java
File metadata and controls
46 lines (41 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// class Solution {
// public boolean wordPattern(String pattern, String s) {
// HashMap<String,String> hm=new HashMap<>();
// String[] words = s.split("\\s+");
// for(int i=0;i<pattern.length();)
// {
// if(hm.containsKey(pattern.charAt(i)))
// {
// if(!hm.get(pattern.charAt(i)).equals(words[i++]))
// return false;
// }
// else{
// if(hm.containsValue(words[i]))
// return false;
// hm.put(pattern.charAt(i)+"",words[i++]);
// }
// }
// return true;
class Solution {
public boolean wordPattern(String pattern, String s) {
HashMap<Character,String> mp = new HashMap<>();
char[] alpha = pattern.toCharArray();
String[] words = s.split("\\s+");
if(words.length!=pattern.length()) return false;
int i=0;
for(char ch : alpha){
if(mp.containsKey(ch)){
if(!mp.get(ch).equals(words[i++]))
return false;
}
else{
if(mp.containsValue(words[i]))
return false;
mp.put(ch,words[i++]);
}
}
return true;
}
}
// }
// }