LeetCode 290. Word Pattern


Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

You may assume pattern contains only lowercase letters, and strcontains lowercase letters that may be separated by a single space.

This problem is similar to 205. Isomorphic String. The difference is problem 205 we compare two strings but this problem we compare a pattern string with a string built with different words. This time we map pattern string to a new string and map str to a new string too.

First, we create a function to map string array to a new string.

Then we can split pattern string and words string to string arrays, then map then to two new string, compare them:


To see more hashtable related problems, see 
Problems and Solutions of Hashmap.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.