simple Java,using HashMap


  • 0
    H
      public boolean wordPattern(String pattern, String str) {
        Map<Character,String> relationMap = new HashMap<Character,String>();
        String strs[] = str.split(" ");
        if(strs.length != pattern.length())
            return false;
        for(int i = 0;i<pattern.length();i++){
            char patternWord = pattern.charAt(i);
            if(!relationMap.containsKey(patternWord)
                    && !relationMap.containsValue(strs[i]))
                    relationMap.put(patternWord,strs[i]);
            else if(!relationMap.containsKey(patternWord)
                    || !relationMap.containsValue(strs[i]))
                    return false;
            else if(relationMap.containsKey(patternWord)
                    && relationMap.containsValue(strs[i]))
                    if(!(relationMap.get(patternWord).equals(strs[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.