Sunday, September 16, 2018

290. Word Pattern

二刷 06/2022
Version #1 Map + Set
一刷的map.containsValue应该是O(N)的complexity
同时如果用s.split("\\s+")就会非常慢
由于题目已经说了是devided by single space,所以可以直接s.split(" ")
Time O(N)
Space O(M) ~ O(1) Since M is at most 26

Runtime: 1 ms, faster than 97.13% of Java online submissions for Word Pattern.
Memory Usage: 42 MB, less than 47.49% of Java online submissions for Word Pattern.
class Solution {
    public boolean wordPattern(String pattern, String s) {
        String[] words = s.split(" ");
        if (pattern.length() != words.length) {
            return false;
        }
        Map<Character, String> map = new HashMap<>();
        Set<String> wordSet = new HashSet<>();
        for (int i = 0; i < pattern.length(); i++) {
            char p = pattern.charAt(i);
            if (map.containsKey(p)) {
                if (!words[i].equals(map.get(p))) {
                    return false;
                }
            } else {
                if (wordSet.contains(words[i])) {
                    return false;
                }
                map.put(p, words[i]);
                wordSet.add(words[i]);
            }
        }
        return true;
    }
}

一刷
Version #1 Map from pattern char to word string
Time O(n^2)
Space O(n)
29.13 %
key is check if map containsValue(words[i]) to avoid multiple patern character map th the same word
class Solution {
    public boolean wordPattern(String pattern, String str) {
        if (pattern == null || str == null) {
            return false;
        }
        String[] words = str.split("\\s+");
        if (pattern.length() != words.length) {
            return false;
        }
        Map<Character, String> map = new HashMap<>();
        for (int i = 0; i < pattern.length(); i++) {
            char c = pattern.charAt(i);
            if (map.containsKey(c)) {
                if (!map.get(c).equals(words[i])) {
                    return false;
                }
            } else {
                if (map.containsValue(words[i])) {
                    return false;
                }
                map.put(c, words[i]);
            }
        }
        return true;
    }
}

No comments:

Post a Comment