Untitled
unknown
plain_text
8 months ago
1.3 kB
6
Indexable
import java.util.*;
public class WordPattern {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (pattern.length() != words.length) {
return false;
}
Map<Character, String> charToWord = new HashMap<>();
Set<String> wordSet = new HashSet<>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String word = words[i];
if (charToWord.containsKey(c)) {
if (!charToWord.get(c).equals(word)) {
return false;
}
} else {
if (wordSet.contains(word)) {
return false;
}
charToWord.put(c, word);
wordSet.add(word);
}
}
return true;
}
public static void main(String[] args) {
WordPattern solution = new WordPattern();
// Test cases
System.out.println(solution.wordPattern("abba", "dog cat cat dog")); // true
System.out.println(solution.wordPattern("abba", "dog cat cat fish")); // false
System.out.println(solution.wordPattern("aaaa", "dog cat cat dog")); // false
}
}
Editor is loading...
Leave a Comment