-
Notifications
You must be signed in to change notification settings - Fork 277
/
WordPattern.java
32 lines (30 loc) · 1.02 KB
/
WordPattern.java
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
// Time complexity => O(n), where n is the length of the pattern
// Space complexity is O(n) where n is the no of words in the map
class WordPattern {
public boolean wordPattern(String pattern, String str) {
Map<Character, String> map = new HashMap<>();
Set<String> set = new HashSet<>();
String[] strValues=str.split(" ");
if(strValues.length !=pattern.length()) {
return false;
}
for(int i=0;i<pattern.length();i++){
Character key = pattern.charAt(i);
String strValue = strValues[i];
if(map.containsKey(key)){
String existingValue = map.get(key);
if(!existingValue.equals(strValue)){
return false;
}
} else {
if(set.contains(strValue)){
return false;
} else{
set.add(strValue);
map.put(key, strValue);
}
}
}
return true;
}
}