Simple java 1 hashmap solution


  • 0
    F

    public class Solution {
    public boolean wordPattern(String pattern, String str) {
    if (pattern.equals("") || str.equals("")) return false;
    String[] patternArray = pattern.split("");
    String[] wordArray = str.split(" ");
    if (patternArray.length != wordArray.length) return false;

        HashMap<String, String> map = new HashMap<String, String>();
        
        for (int i = 0; i < wordArray.length; i++) {
            boolean containsValue = map.containsValue(wordArray[i]);
            boolean containsKey = map.containsKey(patternArray[i]);
            if (!containsKey && !containsValue) {
                //add to map
                map.put(patternArray[i], wordArray[i]);
            }
            else if (containsKey) {
                //check if word match
                if (!map.get(patternArray[i]).equals(wordArray[i])) return false;
            }
            else if (containsValue) {
                for (String key : map.keySet()) {
                    if (key != patternArray[i]) return false;
                }
            }
        }
        
        return true;
    }
    

    }

    //1 dont forget to use equals() when compare between strings
    //2 the second else if was missing for my earlier submissions, not only check keys, but also check values
    //3 the corner cases are so tricky


  • 0
    S

    Nice Solution. Doing it with one hashmap was a subtle thing.


  • 0
    R

    but iterator map too map times


Log in to reply
 

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