My 3ms java solution


  • 0
    R
    public boolean wordPattern(String pattern, String str) {
        if (pattern == null || str == null) return false;
    
        String[] strings = str.split(" ");
    
        if (pattern.length() != strings.length) return false;
    
        HashMap<Character, String> patternHash = new HashMap<>();
        for (int i = 0; i < pattern.length(); ++i) {
            char c = pattern.charAt(i);
            if (!patternHash.containsKey(c) && patternHash.values() != null &&
                    !patternHash.values().contains(strings[i])) {
                patternHash.put(c, strings[i]);
            } else {
                if (!patternHash.containsKey(c) && patternHash.values() != null &&
                        patternHash.values().contains(strings[i]))
                    return false;
                if (patternHash.get(c) != null && !patternHash.get(c).equals(strings[i]))
                    return false;
            }
        }
        return true;
    }

Log in to reply
 

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