DEV Community

Tanuja V
Tanuja V

Posted on • Edited on

Word Pattern - LeetCode - Java

Word Pattern is a problem which is solved using Hashmap

Let's take a look at some examples for better understanding of the question.

Example 1:

Input : pattern = "abba", s = "dog cat cat dog"
Output : true
Explanation : 'a' is mapped with dog and 'b' is mapped with cat

Example 2:

Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Explanation : a -> dog
b -> cat
a -> fish (Since 'a' is already mapped with dog and it cannot be used to map again with some other string. Hence, the result false)

Example 3: (An important test case)

Input : pattern = "abba", s = "dog dog dog dog"
Output : false
Explanation : a -> dog
b -> dog
(Since 'a' is mapped with dog and 'b' is also mapping the same string. Hence, the result false)

Code

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

        String arr[] = s.split(" ");
        int n = arr.length;

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

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

        for(int i=0; i<n; i++){
            char ch = pattern.charAt(i);

            if(map.containsKey(ch) && !(map.get(ch).equals(arr[i])))
                return false;

            if(!map.containsKey(ch) && map.containsValue(arr[i]))
                return false;

            map.put(ch, arr[i]);
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Top comments (0)