-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathword-pattern.java
More file actions
28 lines (24 loc) · 996 Bytes
/
Copy pathword-pattern.java
File metadata and controls
28 lines (24 loc) · 996 Bytes
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
class Solution {
// Time Complexity: O(n)
// Space Complexity: O(n)
public boolean wordPattern(String pattern, String sentence) {
String[] words = sentence.split(" ");
if (pattern.length() != words.length) return false;
Map<Character, String> charToWord = new HashMap<>();
Set<String> mappedWords = new HashSet<>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String word = words[i];
// If pattern character is new
if (!charToWord.containsKey(c)) {
// Word already mapped to another char → invalid pattern
if (mappedWords.contains(word)) return false;
charToWord.put(c, word);
mappedWords.add(word);
}
// Existing mapping must match
else if (!charToWord.get(c).equals(word)) return false;
}
return true; // All mappings are consistent
}
}