Word Pattern – LeetCode – Java

Rmag Breaking News

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;
}
}

Thanks for reading🥰.
Feel free to comment🖌️ and like the post💓
Follow for more 🤝 && Happy Coding🚀👩‍💻

Don’t forget to check-out my other socials😍:
Github
Hashnode
Medium
Twitter(X)

Leave a Reply

Your email address will not be published. Required fields are marked *