JAVA: Using Two HashMaps


  • -1
    F
    public boolean wordPattern(String pattern, String str) {
            String[] words = str.trim().split("\\W+");
            if (pattern.length() != words.length) {
                return false;
            }
            Map<Character, String> map1 = new HashMap<>();
            Map<String, Character> map2 = new HashMap<>();
            for (int i = 0; i < words.length; i++) {
                char tmp1 = pattern.charAt(i);
                String tmp2 = words[i];
                if (map1.containsKey(tmp1) != map2.containsKey(tmp2)) {
                    return false;
                } else if (!map1.containsKey(tmp1)) {
                    map1.put(tmp1, tmp2);
                    map2.put(tmp2, tmp1);
                }
            }
            return true;
        }

  • 0
    C
    "abba"
    
    "dog cat dog dog"
    

    return true

    Expected answer

    false

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.