LeetCode 290: Word Pattern Solution
Master LeetCode problem 290 (Word Pattern), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
290. Word Pattern
Problem Explanation
Explanation
To solve this problem, we can use a HashMap to store the mapping between characters in the pattern and words in the string. We iterate through each character in the pattern and each word in the string, updating the mapping accordingly. If at any point we find a mismatch in the mapping or encounter a word that has already been assigned to a different character, we return false. If we successfully map all characters to words and vice versa, we return true.
- Time Complexity: O(n), where n is the length of the pattern or the number of words in the string.
- Space Complexity: O(n), where n is the number of unique characters in the pattern or unique words in the string.
Solution Code
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (pattern.length() != words.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)) {
if (!charToWord.get(c).equals(word)) {
return false;
}
} else {
charToWord.put(c, word);
}
if (wordToChar.containsKey(word)) {
if (wordToChar.get(word) != c) {
return false;
}
} else {
wordToChar.put(word, c);
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 290 (Word Pattern)?
This page provides optimized solutions for LeetCode problem 290 (Word Pattern) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 290 (Word Pattern)?
The time complexity for LeetCode 290 (Word Pattern) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 290 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 290 in Java, C++, or Python.