DEV Community

Debesh P.
Debesh P.

Posted on

290. Word Pattern | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/word-pattern/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/word-pattern/solutions/7490201/most-optimal-solution-beats-200-hashmap-endc9


leetcode 290


Solution

class Solution {
    public boolean wordPattern(String pattern, String s) {

        String[] words = s.split(" ");

        if (pattern.length() != words.length) return false;

        Map<Character, String> charWord = new HashMap<>();
        Map<String, Character> wordChar = new HashMap<>();

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

            if (charWord.containsKey(ch)) {
                if (!charWord.get(ch).equals(word)) {
                    return false;
                }
            } else if (wordChar.containsKey(word)) {
                return false;
            } else {
                charWord.put(ch, word);
                wordChar.put(word, ch);
            }
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)