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.

Examples:

pattern = "abba", str = "dog cat cat dog" should return true. pattern = "abba", str = "dog cat cat fish" should return false. pattern = "aaaa", str = "dog cat cat dog" should return false. pattern = "abba", str = "dog dog dog dog" should return false.

Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

Credits:Special thanks to @minglotus6 for adding this problem and creating all test cases.

Solution

public class Solution {
    public boolean wordPattern(String pattern, String str) {
             if (pattern == null || pattern.isEmpty()) return false;
        if (str == null || str.isEmpty()) return false;

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

        String[] array = str.split(" ");

        if (array.length != pattern.length()) {
            return false;
        }

        for (int i = 0; i < array.length; i++) {
            String p = pattern.substring(i, i + 1);
            String c = array[i];

            if (map.containsKey(p)) {
                if (!c.equals(map.get(p))) {
                    return false;
                }
            } else {
                map.put(p, c);
            }

            if (map2.containsKey(c)) {
                if (!p.equals(map2.get(c))) {
                    return false;
                }
            } else {
                map2.put(c, p);
            }
        }

        return true;
    }
}

results matching ""

    No results matching ""