Skip to content
Open

Added #3397

Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions wordPattern.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (words.length != pattern.length()) {
return false;
}

Map<Character, String> charToWord = new HashMap<>();
Map<String, Character> wordToChar = new HashMap<>();

for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String word = words[i];

if (!charToWord.containsKey(c)) {
charToWord.put(c, word);
}

if (!wordToChar.containsKey(word)) {
wordToChar.put(word, c);
}

if (!charToWord.get(c).equals(word) || !wordToChar.get(word).equals(c)) {
return false;
}
}

return true;
}
}
Loading